递归遍历二叉树的所有可能路径就好了
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, path = [], []
def dfs(root, cur):
if not root:
return
path.append(root.val)
cur = cur - root.val
if cur == 0 and not root.left and not root.right:
res.append(list(path)) #注意这里要加List,不然下次path改变会导致res中已经添加的path改变
dfs(root.left, cur)
dfs(root.right, cur)
path.pop() #注意这里的cur没有执行cur += root.val 应该是因为cur属于函数的参数会随着自己变化
dfs(root, sum)
return res