思路:dfs,遍历过程中记录路径,到达叶子时判断是否满足sum为target,如果满足,记录下来

注意:

1、递归过程中,有个坑,path加入result的时候,要复制path 2、遍历完,返回上层前,要pop掉路径中记录的尾部 3、path += [val]、path.append(val)和path = path + [val]会引起结果不同

class Solution:
    def FindPath(self , root: TreeNode, target: int) -> List[List[int]]:
        # write code here
        
        if not root:
            return []
        
        self.result = []
        path = []
        self.dfs(root, target, path)
        return self.result
        
    def dfs(self, root, target, path):
        if not root:
            return
        
        path = path + [root.val] # 要用此写法,+=和append会报错

        if not root.left and not root.right and sum(path) == target:
            self.result.append(path)

        if root.left:
            self.dfs(root.left, target, path)
        if root.right:
            self.dfs(root.right, target, path)