题解 | #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
};
全部评论

相关推荐

04-03 22:41
兰州大学 C++
老六f:有时候是HR发错了,我之前投的百度的后端开发,他给我发的算法工程师,但是确实面的就是百度开发
点赞 评论 收藏
分享
万物DP:目前可以说没机会了,offer在4月都发完了。把实习用AI改一改投中小厂吧
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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