> For the complete documentation index, see [llms.txt](https://kerasnoone.gitbook.io/garnet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kerasnoone.gitbook.io/garnet/suan-fa/shu/113-lu-jing-zong-he-ii.md).

# \[113]\[中等]\[DFS] 路径总和 II

## 题目描述

[113. 路径总和 II](https://leetcode-cn.com/problems/path-sum-ii/) [剑指 Offer 34. 二叉树中和为某一值的路径](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/)

给定一个二叉树和一个目标和，找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例: 给定如下二叉树，以及目标和 sum = 22，

```
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
```

返回:

```
[
   [5,4,11,2],
   [5,8,4,5]
]
```

## 解题思路

追随树的路径, 使用DFS的思路搜索, 路径上不断减去遇到的结点的值, 直到遇到叶子结点, 判断减去后是否为0, 如果为0, 将这条路径上遇到的所有结点值组成的数组添加到最终的结果中.

* 根据上面的过程, 递归的函数要传递**当前结点**, **剩余值**, **当前列表**
* 因为要遍历所有结点, 当前路径是以列表的形式递归传递, 因此要做好**回溯**工作, 在遍历完某个结点及其代表的子树, 要返回到上层时, 要恢复路径列表, 将这个数从路径中剔除

```python
# 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 = []
        def dfs(node, resi, path):
            if node is None:
                return
            if node is not None and node.left is None and node.right is None:
                if resi == node.val:
                    t = deepcopy(path)
                    t.append(node.val)
                    res.append(t)
                return

            resi -= node.val
            path.append(node.val)
            dfs(node.left, resi, path)
            dfs(node.right, resi, path)
            path.pop()

        dfs(root, sum, [])
        return res
```
