257. Binary Tree Paths [easy] (Python)

题目链接

https://leetcode.com/problems/binary-tree-paths/

题目原文

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   2     3
   5

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

题目翻译

给定一个二叉树,返回所有从根到叶子的路径。

思路方法

思路一

递归实现深度优先遍历。注意要记录途中访问过的节点,遇到叶子节点时可以生成一条路径字符串。关于记录路径,一般的方法(后面几种思路的方法)是直接将目前为止的路径字符串记录下来,而下面的代码采用先保存在数组里需要生成路径时再生成的方法,大家可以对照比较一下。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        res, path_list = [], []
        self.dfs(root, path_list, res)
        return res

    def dfs(self, root, path_list, res):
        if not root:
            return
        path_list.append(str(root.val))
        if not root.left and not root.right:
            res.append(‘->‘.join(path_list))
        if root.left:
            self.dfs(root.left, path_list, res)
        if root.right:
            self.dfs(root.right, path_list, res)
        path_list.pop()

思路二

上面的递归定义了一个额外的helper function——dfs(),用于传递和保存递归的信息。其实可以直接用原函数做递归,代码如下。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        res = []
        if not root:
            return res
        if not root.left and not root.right:
            res.append(str(root.val))
            return res
        for path in self.binaryTreePaths(root.left):
            res.append(str(root.val) + ‘->‘ + path)
        for path in self.binaryTreePaths(root.right):
            res.append(str(root.val) + ‘->‘ + path)
        return res

思路三

有递归DFS代码,就可以用栈实现DFS。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        res, stack = [], [(root, ‘‘)]
        while stack:
            node, curs = stack.pop()
            if node:
                if not node.left and not node.right:
                    res.append(curs + str(node.val))
                stack.append((node.left, curs + str(node.val) + ‘->‘))
                stack.append((node.right, curs + str(node.val) + ‘->‘))
        return res

思路四

同样的,用队列实现BFS也可以完成要求。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        res, queue = [], [(root, ‘‘)]
        while queue:
            node, curs = queue.pop()
            if node:
                if not node.left and not node.right:
                    res.append(curs + str(node.val))
                queue.insert(0, (node.left, curs + str(node.val) + ‘->‘))
                queue.insert(0, (node.right, curs + str(node.val) + ‘->‘))
        return res

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:http://blog.csdn.net/coder_orz/article/details/51706119

时间: 2024-10-12 19:52:31

257. Binary Tree Paths [easy] (Python)的相关文章

<LeetCode OJ> 257. Binary Tree Paths

257. Binary Tree Paths My Submissions Question Total Accepted: 29282 Total Submissions: 113527 Difficulty: Easy Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["

leetCode 257. Binary Tree Paths 二叉树路径

257. Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree:    1  /   2     3    5 All root-to-leaf paths are: ["1->2->5", "1->3"] 思路: 1.采用二叉树的后序遍历非递归版 2.在叶子节点的时候处理字

(easy)LeetCode 257.Binary Tree Paths

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 思想:递归代码如下: /** * Definition for a binary tree node. * public class Tre

【leetcode?python】 257. Binary Tree Paths

深度优先搜索 # Definition for a binary tree node.# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = None class Solution:    # @param {TreeNode} root    # @return {string[]}        resultList=

【easy】257. Binary Tree Paths 二叉树找到所有路径

http://blog.csdn.net/crazy1235/article/details/51474128 花样做二叉树的题--居然还是不会么-- /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ cl

Java [Leetcode 257]Binary Tree Paths

题目描述: Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 解题思路: 使用递归法. 代码如下: /** * Definition for a binary tree node. * pu

LeetCode 257. Binary Tree Paths (二叉树路径)

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 题目标签:Tree 这道题目给了我们一个二叉树,让我们记录所有的路径,返回一个array string list. 我们可以另外设一个fin

重做257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] Solution1: 用string是最方便的.因为string是immutable的,所以当返回的时候不会带回最后加的string. /*

257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are: ["1->2->5", "1->3"] 用backtracking的方法.与113题很类似.需要注意其实root元素 public IList<string> Bina