LeetCode in TypeScript

102. Binary Tree Level Order Traversal

Medium

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

Example 1:

Input: root = [3,9,20,null,null,15,7]

Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]

Output: [[1]]

Example 3:

Input: root = []

Output: []

Constraints:

Solution

import { TreeNode } from '../../com_github_leetcode/treenode'

/*
 * 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 = [root]
    let result = []
    while (queue.length != 0) {
        let subResult = []
        let length = queue.length
        while (length > 0) {
            let node = queue.shift()
            subResult.push(node.val)
            if (node.left != null) queue.push(node.left)
            if (node.right != null) queue.push(node.right)
            length--
        }
        result.push(subResult)
    }
    return result
}

export { levelOrder }