Skip to content

Latest commit

 

History

History
56 lines (48 loc) · 1.51 KB

38_二叉树_102. 二叉树的层序遍历.md

File metadata and controls

56 lines (48 loc) · 1.51 KB

-- 二叉树 - mid 点击直达力扣

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

实例 1:

输入: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.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
// 队列
function levelOrder(root: TreeNode | null): number[][] {
    if (root === null) {
        return []
    }
    let queue = []
    let result = []
    queue.push(root)
    while (queue.length != 0) {
        let vec = []
        let size = queue.length  // 使用size记录每一层元素的大小
        while (size--) {  // 记录每一层元素,并将下一层元素存储于队列中
            let node = queue.shift()
            if (node != null) { vec.push(node.val) }
            if (node.left) { queue.push(node.left) }
            if (node.right) { queue.push(node.right) }
        }
        result.push([...vec])
    }
    return result
};