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

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

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

相关推荐

king122:专业技能不要写这么多,熟悉和熟练你经不住问,排版有些难看,中间的空隙搞小一点,项目描述的话感觉是从课程中抄下来的,改一改吧,不然烂大街了,每个项目都写一两点,用什么技术实现了什么难点,然后再写一些数字上去像时间又花了90%这样,这样面试会多一些,如果觉得自己的项目还是不够用的话,我有几个大厂最近做过的实习项目,感兴趣的话可以看我简介中的项目地址
点赞 评论 收藏
分享
nus22016021404:兄弟,你这个简历撕了丢了吧,就是一坨,去找几个项目,理解项目流程,看几遍就是你的了,看看八股就去干了,多看看牛客里别人发出来的简历,对着写,你这写的啥啊,纯一坨
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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