Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

二叉树的层序遍历

Sunny-117 opened this issue · comments

var levelOrder = function(root) {
    if(!root) return [];
    let res = [];
    let queue = [root];

    while(queue.length){
        //记录当前层级节点数
        let len = queue.length;
        //存放每一层的节点
        let curLevel = [];
        for(let i = 0; i < len; i++){
            let node = queue.shift();
            curLevel.push(node.val);
            //存入下一层的节点
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
        res.push(curLevel);
    }
    return res;
};