题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
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
需要注意的是,节点的值有可能是负数。
