Skip to content
On this page

LeetCode 从上到下打印二叉树1

alt

😈 利用队列的先进先出很容易办到,遍历每一层的节点

js
var levelOrder = function(root) {
    const res = [];
    if (!root) {
        return res;
    }
    const q = [];
    q.push(root);
    while (q.length !== 0) {
        const currentLevelSize = q.length;
        //每一层节点的数量
        for (let i = 1; i <= currentLevelSize; ++i) {
            const node = q.shift();
            //弹出队列
            res.push(node.val);
            // 将下一层的节点放入队列
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
    }
        
    return res;
};


LeetCode 从上到下打印二叉树2

alt 😊 提前准备好一个数组push进去即可

js
var levelOrder = function(root) {
    const res = [];
    if (!root) {
        return res;
    }

    const q = [];
    q.push(root);
    while (q.length !== 0) {
        console.log(q.length)
        const currentLevelSize = q.length;
        res.push([]);
        for (let i = 1; i <= currentLevelSize; ++i) {
            const node = q.shift();
            res[res.length - 1].push(node.val);
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
    }
        
    return res;
};

LeetCode 从上到下打印二叉树3

alt 🤗 没什么难的 reverse即可

js
var levelOrder = function(root) {
    const res = [];
    if (!root) {
        return res;
    }
    const q = [];
    q.push(root);
    while (q.length !== 0) {
        console.log(q.length)
        const currentLevelSize = q.length;
        res.push([]);
        for (let i = 1; i <= currentLevelSize; ++i) {
            const node = q.shift();
            res[ret.length - 1].push(node.val);
            if (node.left) q.push(node.left);
            if (node.right) q.push(node.right);
        }
        if(res.length%2==0)
        {
            res[ret.length-1].reverse()
        }
    }
        
    return res;
};

👹好的,今天的层序遍历我们到此结束