题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function FindPath(root, expectNumber)
{
// write code here
const path = [];
const result = [];
this.findSumPath = function(node,sum) {
if(node === null) return;
path.push(node.val);//非空把节点值放入path
sum -= node.val;//减去走过节点的值
// 遍历到叶子节点且满足路径和
if(node.left === null && node.right === null && sum === 0) {
result.push([...path]);//放进result时注意解构拷贝path
}
//先序遍历: 递归左 / 右子节点
this.findSumPath(node.left,sum);
this.findSumPath(node.right,sum);
//路向上回溯前,需要将当前节点从路径 path 中删除
path.pop();
}
this.findSumPath(root,expectNumber);
return result;
}
module.exports = {
FindPath : FindPath
};

查看3道真题和解析
