用js刷剑指offer(二叉树中和为某一值的路径)
题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
js代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
res = []
temp = []
function FindPath(root, expectNumber)
{
// write code here
if (!root) return res
temp.push(root.val)
expectNumber -= root.val
if ((expectNumber === 0) && (!root.left) && (!root.right)) {
res.push(temp.concat([]))
}
FindPath(root.left, expectNumber)
FindPath(root.right, expectNumber)
temp.pop()
return res
}
module.exports = {
FindPath : FindPath
};