题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

思路:dfs,遍历过程中记录路径,到达叶子时判断是否满足sum为target,如果满足,记录下来

注意:

1、递归过程中,有个坑,path加入result的时候,要复制path 2、遍历完,返回上层前,要pop掉路径中记录的尾部 3、path += [val]、path.append(val)和path = path + [val]会引起结果不同

class Solution:
    def FindPath(self , root: TreeNode, target: int) -> List[List[int]]:
        # write code here
        
        if not root:
            return []
        
        self.result = []
        path = []
        self.dfs(root, target, path)
        return self.result
        
    def dfs(self, root, target, path):
        if not root:
            return
        
        path = path + [root.val] # 要用此写法,+=和append会报错

        if not root.left and not root.right and sum(path) == target:
            self.result.append(path)

        if root.left:
            self.dfs(root.left, target, path)
        if root.right:
            self.dfs(root.right, target, path)
          
全部评论

相关推荐

06-27 15:29
门头沟学院 Java
点赞 评论 收藏
分享
就在我现在公司的隔壁每天经过都唏嘘不已(就是羡慕)什么时候可以到这里上班啊
柯基在debug:从大学毕业投简历到现在了,应届的时候我都面到终面了,现在工作四年了连简历初筛都过不了了
投递莉莉丝游戏等公司8个岗位
点赞 评论 收藏
分享
大飞的诡术妖姬:之前看b站多明海有个说法,日本就业竞争非常低的原因不光是毕业学生少,还有很多人干两年不喜欢职场氛围就辞职躺平,位置也空了很多,论吃苦耐劳还得看咱们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务