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

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

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
};

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

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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