解题思路:dfs+回溯,用dfs遍历所有从根节点到叶节点路径,并记录路径上的值,如果和等于目标值,就将这条路径添加到结果中,不等于就返回,当一颗紫薯遍历完之后就弹出根节点,尝试父节点的另一个节点构成的路径,不断回溯,直至遍历完所有的路径
# 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]]:
if root is None:
return []
res = []
def traceback(num, root, path):
if root.left is None and root.right is None:
if num == root.val:
res.append(path[:]+[root.val])
return
path.append(root.val)
if root.left:
traceback(num - root.val, root.left, path)
if root.right:
traceback(num - root.val, root.right, path)
path.pop()
traceback(sum, root, [])
return res