题目:给定一个节点数为 n 的二叉树和一个值 sum ,请找出所有的根节点到叶子节点的节点值之和等于的路径,如果没有则返回空。
例如:
给出如下的二叉树,sum = 22 ,
牛客题目地址:https://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a
例如:
(1)
输入:{1,2},1
返回值:[]
说明:此树只有一条路径,即[1,2]大于sum,所以输出空。
(2)
输入:{1,2},3
返回值:[[1,2]]
用JavaScript实现深度遍历在回溯,但是用例只能通过13个,后续排查,也请看到的大佬帮我看看,感谢。
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型二维数组
*/
function deepCopy(arr) {
let res = []
for (let i=0; i < arr.length; i++) {
res.push(arr[i])
}
return res
}
const ans=[]
function preorder(root,sum,tmp){
if(!root) return
sum-=root.val
tmp.push(root.val)
if(root.left===null&&root.right===null){
if(sum===0){
const tmp2 = deepCopy(tmp)
ans.push(tmp2)
tmp.length = tmp.length - 1
}
return
}
if(root.left) preorder(root.left,sum,tmp)
if(root.right) preorder(root.right,sum,tmp)
tmp.length = tmp.length - 1
return
}
function pathSum( root , sum ) {
// write code here
if(!root) return ans
let tmp=[]
preorder(root,sum,tmp)
return ans
}
module.exports = {
pathSum : pathSum
};