跳至主要內容

Mr.He小于 1 分钟

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    // 1. 如果根节点为空,直接返回空数组
    if (!root) return [];

    // 2. 初始化结果数组 和 队列(将根节点入队)
    const res = [];
    const queue = [root];

    // 3. 当队列不为空时循环
    while (queue.length > 0) {
        // 记录当前层的节点数量
        const levelSize = queue.length;
        // 当前层的节点值数组
        const currentLevel = [];

        // 遍历当前层的所有节点
        for (let i = 0; i < levelSize; i++) {
            // 从队列头部取出节点
            const node = queue.shift();
            
            // 将节点值存入当前层数组
            currentLevel.push(node.val);

            // 如果有左子节点,入队
            if (node.left) {
                queue.push(node.left);
            }
            // 如果有右子节点,入队
            if (node.right) {
                queue.push(node.right);
            }
        }

        // 将当前层的结果推入总结果数组
        res.push(currentLevel);
    }

    // 4. 返回结果
    return res;
};