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

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

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

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param root TreeNode类 
# @param target int整型 
# @return int整型二维数组
#
class Solution:
    def findSubPath(self,root:TreeNode,path: List[int],paths:List[List[int]],target: int):       
        print(root.val,path) 
        path.append(root.val)
        if sum(path) == target:
            if root.left is None and root.right is None:
                paths.append(path)
        else:
            path_left = path
            path_right = path.copy()
            if root.left is not None :
                self.findSubPath(root.left,path_left,paths,target)
            if root.right is not None :
                self.findSubPath(root.right,path_right,paths,target)

    def FindPath(self , root: TreeNode, target: int) -> List[List[int]]:
        # write code here
        # 涉及深度遍历,需要递归
        paths=[]
        path = []
        if root is None:
            return []
        path.append(root.val)
        path_left = path
        path_right = path.copy()
        if sum(path) == target:
            if root.left is None and root.right is None:
                paths.append(path)
        if root.left is not None:
            self.findSubPath(root.left,path_left,paths,target)
        if root.right is not None:
            self.findSubPath(root.right,path_right,paths,target)
        return paths

需要注意的是,节点的值有可能是负数。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:23
转人工😡
门口唉提是地铁杀:五次握手了
点赞 评论 收藏
分享
06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
07-01 13:37
门头沟学院 Java
steelhead:不是你的问题,这是社会的问题。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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