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

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

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

相关推荐

AAA专业长城贴瓷砖刘大爷:这样的简历我会直接丢进垃圾桶,花里胡哨的
点赞 评论 收藏
分享
03-25 19:00
东北大学 Java
程序员牛肉:太好了,是聊天记录。不得不信了。 当个乐子看就好,不要散播焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务