题目描述
解法:dfs递归
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
paths, path = [], []
def recur(node, tar):
if not node:
return
path.append(node.val)
t = tar - node.val
if t == 0 and not node.left and not node.right:
paths.append(list(path))
recur(node.left,t)
recur(node.right,t)
path.pop()
recur(root, target)
return paths
注意事项:
paths.append(list(path))等同于复制了一个path,才能保证加入paths后的list不会被后续操作修改
paths.append(path)会导致paths中的path一直在改变