102. 二叉树的层序遍历

67 阅读1分钟

好青年 | leetcode 打卡群 - 打卡记录第 十一 天

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

 

示例 1:

image.png

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]
/**
 * 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) {
    if (!root) return [];
    // 初始化层级为0
    const stack = [[root, 0]];
    let res = [];
    while (stack.length) {
        const [n, l] = stack.shift();

        if (!res[l]) {
            res.push([n.val])
        } else {
            res[l].push(n.val)
        }
        if (n.left) stack.push([n.left, l + 1]);
        if (n.right) stack.push([n.right, l + 1]);
    }

    return res
};