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

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

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

这个过程就是深度遍历的过程,用期望值减去走过的上一个节点,检查结果是否为0,若为0,则退出,反之继续遍历。每一次都是先检查左节点,再检查右节点,若左节点符合,先深度遍历左节点,之后遍历右节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function FindPath(root, expectNumber)
{
// write code here
const list=[],listAll=[];
return find(root,expectNumber,list,listAll);

}
function find(root,expectNumber,list,listAll){
if(root==null){
return listAll;
}
list.push(root.val);
const x=expectNumber-root.val;
if(root.left==null&&root.right==null&&x==0){
listAll.push(Array.of(...list));
}
find(root.left,x,list,listAll);
find(root.right,x,list,listAll);
list.pop();
return listAll;
}