# 二叉树中和为某一值的路径|博客系列

> 本文详细讲解如何在二叉树中查找所有节点值之和等于给定目标值的路径，包括题目描述、解题思路和 JavaScript 代码实现，适合数据结构与算法学习者参考。

- 原文：https://feinterview.poetries.top/docs/fe-blog-docs/blog-docs/data-struct/16-%E4%BA%8C%E5%8F%89%E6%A0%91%E4%B8%AD%E5%92%8C%E4%B8%BA%E6%9F%90%E4%B8%80%E5%80%BC%E7%9A%84%E8%B7%AF%E5%BE%84
- 来源：前端进阶之旅（feinterview.poetries.top）
- 更新：2025.10.25

---

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

#### 题目描述

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

#### 解题思路

1. 每次到新的节点上，都记录新的节点的值；
2. 判断新的节点是否是叶子节点，若是叶子节点则判断路径上节点值的总和是否符合条件；若不是，则继续递归处理左右子树；
3. 最后需要将新节点的信息清除。

#### coding

```javascript
class Node {
  constructor (value, left = null, right = null) {
    this.value = value;
    this.left = left;
    this.right = right;
  }
}
/*
* 根据 target 返回某一路径
* param {Tree} tree
* param {Number} target
*/
function searchPath (tree, target) {
    let sum = 0, // 路径上的节点的值的总和
    paths = []; // 存放所有满足条件的路径

    function _searchPath (node, path) {
        if (node === null) {
            return
        }
        
        sum = sum + node.value; // 计算总和
        path.push(node); // 将当前节点推入路径中

        // 判断是否是叶子节点
        const isLeaf = node.left === null && node.right === null;

        if (isLeaf && sum === target) { // 若是叶子节点且路径上的节点满足条件则记录这条路径
            paths.push([...path])
        }

        if (node.left !== null) { // 向左子树递归
            _searchPath(node.left, path)
        }
        if (node.right !== null) {
            _searchPath(node.right, path)
        }

        sum = sum - node.value; // 把当前节点从路径中移除, 达到重置的效果
        path.pop();
    }

    _searchPath(tree, []);
    return paths;
}
const tree = new Node(1, new Node(2, new Node(4), new Node(6)), new Node(3, null, new Node(5)));
console.log(searchPath(tree, 9))
```
