257. 二叉树的所有路径

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

解法一:

dfs遍历即可

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        res = []
        def dfs(root, path):    #path记录当前路径
            if not root:    #空节点
                return
            if not root.left and not root.right:    #叶节点
                path.append(str(root.val))
                res.append('->'.join(path))
            dfs(root.left, path + [str(root.val)])
            dfs(root.right, path + [str(root.val)])
        dfs(root, [])
        return res

最后更新于