# 34.二叉树中和为某一值的路径

## 题目

输入一棵二叉树和一个整数，打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

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

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

返回:

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

提示：

节点总数 <= 10000

来源：[力扣（LeetCode）](https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof)

## 题解

将问题拆解为子树的问题，递归解决

```swift
func pathSum(_ root: TreeNode?, _ target: Int) -> [[Int]] {
    guard let rootV = root?.val else {
        return []
    }
    var result: [[Int]] = []
    let deta = target - rootV
    var temp: [TreeNode] = []

    if let left = root?.left {
        temp.append(left)
    }

    if let right = root?.right {
        temp.append(right)
    }

    if temp.isEmpty { // 到达叶节点了
        if target == rootV {
            result.append([rootV])
        }
    }
    else {
        temp.forEach { tree in
            pathSum(tree, deta).forEach { datas in
                result.append([rootV] + datas)
            }
        }
    }

    return result
}
```

![01](/files/-MiuwlJEJZR37OZjmvO-)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/shu-ju-jie-gou-yu-suan-fa/jian-zhi-offerswift/34.-er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
