JavaScript-二叉树根节点到叶子节点和为指定值的路径

题目:给定一个节点数为 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
	};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值