美文网首页
leetcode257. Binary Tree Paths

leetcode257. Binary Tree Paths

作者: 就是果味熊 | 来源:发表于2020-06-22 11:01 被阅读0次

    原题链接https://leetcode.com/problems/binary-tree-paths/
    做到这里的时候已经被前面的dfs的题弄到心力憔悴,这题回了口血,啊哈哈哈

    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

    class Solution:
        def binaryTreePaths(self, root: TreeNode) -> List[str]:
    
            def dfs(root, path, res):
                if not root:
                    return 
                path = path + "->" + str(root.val)
                if not (root.left or root.right):
                    res.append(path[2:])
                dfs(root.left,path,res)
                dfs(root.right,path,res)
            path = ""
            res = []
            dfs(root,path,res)
            return res
    

    相关文章

      网友评论

          本文标题:leetcode257. Binary Tree Paths

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