首页 > 其他 > 详细

leetcood学习笔记-257-二叉树的所有路径

时间:2019-03-28 18:43:43      阅读:73      评论:0      收藏:0      [点我收藏+]

 

题目描述:

技术分享图片

 第一次提交:参考113-路径总和②

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

方法二

class Solution:
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if root == None:
            return []
        if root.left == None and root.right == None:
            return [str(root.val)]
        paths = self.binaryTreePaths(root.left) + self.binaryTreePaths(root.right)
        for i in range(len(paths)):
            paths[i] = str(root.val) + -> + paths[i]
        return paths

 

leetcood学习笔记-257-二叉树的所有路径

原文:https://www.cnblogs.com/oldby/p/10616747.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!