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

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

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

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
var path = [];
var res = [] //存放最终结果
function dfs(root,expectNumber){
    if(root == null){
        return;
    }
    expectNumber -= root.val;
    path.push(root.val); //存放每条路径
    if(expectNumber == 0 && root.left == null && root.right == null){
        res.push(path);
        //下面三句防止push()深拷贝 改为浅拷贝
        temp = path;
        path = [];
        for(let i = 0;i < temp.length;i++){
            path.push(temp[i]);
        }
    }
    dfs(root.left,expectNumber);
    dfs(root.right,expectNumber);
    path.pop(); //回溯 先记住 dfs最后一步都有
}
function FindPath(root, expectNumber)
{
    // write code here
    if(root == null){
        return [];
    }
    dfs(root,expectNumber);
    return res;
}
module.exports = {
    FindPath : FindPath
};

#我的实习求职记录#
全部评论

相关推荐

后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
点赞 评论 收藏
分享
05-09 13:22
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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