美文网首页工作生活
深度优先 广度优先

深度优先 广度优先

作者: lililililiyan | 来源:发表于2019-07-02 10:54 被阅读0次

深度优先:首先遍历最低层的节点,然后逐步上移到根节点。
dfs + recursion过于的慢
尽量不使用递归

  1. Binary Tree Paths
    Easy
    Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

1
/
2 3

5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3
\color{red}{一样都是深度优先搜索搜索,不用递归就是比用递归要快}
自己写的递归

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

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if root is None:
            return []
        ls,res='',[]
        self.dfs(root,ls,res)
        return res
        
    def dfs(self,node,ls,res):
        if node.left:
            self.dfs(node.left, ls+str(node.val)+'->', res)
        if node.right:
            self.dfs(node.right, ls+str(node.val)+'->', res)
        if node.left is None and node.right is None: 
            res.append(ls+str(node.val))

别人写的用栈不用递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#用stack代替递归,会快一些嘞
class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if not root:
            return []
        res,stack=[],[(root,"")]
        while stack:
            node, ls = stack.pop()
            if not node.left and not node.right:
                res.append(ls+str(node.val))
            if node.right:
                stack.append((node.right, ls+str(node.val)+"->"))
            if node.left:
                stack.append((node.left, ls+str(node.val)+"->"))
        return res

二叉树的最大路径和 #124
找不到快一点的方法 有时间再做一次

相关文章

网友评论

    本文标题:深度优先 广度优先

    本文链接:https://www.haomeiwen.com/subject/wwkncctx.html