题解 | #JZ 34二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

```/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function FindPath(root, expectNumber)
{
    // write code here
    //dfs深度优先搜索,记录每一条路径的和值,与目标值比较,相同将该路径推入resArr
    if(root===null){return 0}
    let resArr=[]
    let sum=0
    let tempArr=[]
    dfs(root,expectNumber,tempArr,sum,resArr)
    return resArr
    function dfs(root,expectNumber,tempArr,sum,resArr){
        tempArr.push(root.val)
        sum+=root.val
        if(root.left===null&&root.right===null&&sum===expectNumber){resArr.push(tempArr.slice(0))} //注意深拷贝
        if(root.left){dfs(root.left,expectNumber,tempArr,sum,resArr)} //注意每次都要把变量传递进去
        if(root.right){dfs(root.right,expectNumber,tempArr,sum,resArr)}
        tempArr.pop()
    }
    
}
module.exports = {
    FindPath : FindPath
};
全部评论

相关推荐

10-31 13:04
南华大学 Java
嵌入式的小白:很多面试,面试前不会去打扰cto的,但一般cto不会在这些小事上刷人,只能说这个cto比较操心,啥重要不重要,紧急不紧急的,估计都会过问,平淡看待吧
点赞 评论 收藏
分享
牛客36400893...:我不是这个专业的,但是简历确实没有吸引我的亮点,而且废话太多没耐心看
0offer是寒冬太冷还...
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务