题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
var path = [];
var res = [] //存放最终结果
function dfs(root,expectNumber){
if(root == null){
return;
}
expectNumber -= root.val;
path.push(root.val); //存放每条路径
if(expectNumber == 0 && root.left == null && root.right == null){
res.push(path);
//下面三句防止push()深拷贝 改为浅拷贝
temp = path;
path = [];
for(let i = 0;i < temp.length;i++){
path.push(temp[i]);
}
}
dfs(root.left,expectNumber);
dfs(root.right,expectNumber);
path.pop(); //回溯 先记住 dfs最后一步都有
}
function FindPath(root, expectNumber)
{
// write code here
if(root == null){
return [];
}
dfs(root,expectNumber);
return res;
}
module.exports = {
FindPath : FindPath
};
#我的实习求职记录#
