其他分享
首页 > 其他分享> > 257. 二叉树的所有路径

257. 二叉树的所有路径

作者:互联网

在这里插入图片描述

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    ### DFS
    def binaryTreePaths(self, root):
        def dfs(root, path):
            if root:
                path += str(root.val)
                if not root.left and not root.right:  # 当前节点是叶子节点
                    res.append(path)  # 把路径加入到答案中
                else:
                    path += '->'  # 当前节点不是叶子节点,继续递归遍历
                    dfs(root.left, path)
                    dfs(root.right, path)

        res = []
        dfs(root, '')

        return res
    
    ### BFS
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        res = []
        if not root: return res

        # 两个双端队列,一个存放节点、一个存放路径字符串
        node_q = collections.deque([root])
        path_q = collections.deque([str(root.val)])

        while node_q:
            node = node_q.popleft()
            path = path_q.popleft()

            if not node.left and not node.right: # 到达叶节点
                res.append(path)
            else:
                if node.left:
                    node_q.append(node.left)
                    path_q.append(path + '->' + str(node.left.val))
                
                if node.right:
                    node_q.append(node.right)
                    path_q.append(path + '->' + str(node.right.val))

        return res

标签:node,right,val,路径,二叉树,path,root,257,left
来源: https://blog.csdn.net/newCraftsman/article/details/115384922