您的位置:首页 > Web前端

剑指offer(24)二叉树中和为某一值的路径

2018-03-29 11:53 253 查看

题目描述

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

 

题目分析

这题基本上一看就知道应该深度遍历整个树,并且把已经走过的节点的和与期望值作比较就行,如果走到底还不符合要求的话,就要回退值。

 

代码

function FindPath(root, expectNumber)
{
// write code here
let list=[],listAll=[];
return findpath(root,expectNumber,list,listAll);
}
function findpath(root,expectNumber,list,listAll){
if(root==null){
return listAll;
}
list.push(root.val);
let x=expectNumber-root.val;
if(root.left==null&&root.right==null&&x==0){
listAll.push(Array.of(...list));
}
findpath(root.left,x,list,listAll);
findpath(root.right,x,list,listAll);
list.pop();
return listAll;
}

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: