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

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

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)
          
全部评论

相关推荐

牛客33727151号:不是哥们我以为驾照是段子呢
点赞 评论 收藏
分享
野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务