# 二叉树中和为某一值的路径
# 题目描述
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
# 解题思路
- 每次到新的节点上,都记录新的节点的值;
- 判断新的节点是否是叶子节点,若是叶子节点则判断路径上节点值的总和是否符合条件;若不是,则继续递归处理左右子树;
- 最后需要将新节点的信息清除。
# coding
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))
阅读全文