题解 | #求二叉树的层序遍历-两种方法#

求二叉树的层序遍历

http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

记录下层次

function levelOrder( root ) {
    // write code here
    let res = [];
    if(!root) return res;
    let q = [[root,0]];
    while(q.length){
        let [n,l] = q.shift();
        if(!res[l]){ res.push([n.val])}
        else{res[l].push(n.val)};
        if(n.left) q.push([n.left,l+1]);
        if(n.right) q.push([n.right,l+1]);
    }
    return res;
}

队列中只有某一层节点

function levelOrder( root ) {
    // write code here
    let res = [];
    if(!root) return res;
    let q = [root];
    while(q.length){
        let len = q.length;
//         这里先推入一个空数组
        res.push([]);
        while(len --){
            const head = q.shift();
//             收集结果
            res[res.length - 1].push(head.val);
//             将左右进栈--第二层的
            if(head.left) q.push(head.left);
            if(head.right) q.push(head.right);
        }
    }
    //console.log(res);
    return res;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务