MediumPro challengePythonJavaScriptTypeScript

Binary Tree Level-Order Traversal

Data StructuresTreesBFS

Build a binary tree from a level-order (BFS) serialization array and return
its level-order traversal as a 2D array — one sub-array per level.

Serialization format
The input uses the standard LeetCode format: values are placed left-to-right
per level; null marks an absent child.

[3, 9, 20, null, null, 15, 7]

      3
     / \
    9  20
       / \
      15   7

solve(nodes) must return [[3], [9, 20], [15, 7]].

More examples

solve([1])                            → [[1]]
solve([])                             → []
solve([1, 2, 3, 4, 5])               → [[1], [2, 3], [4, 5]]
solve([1, null, 2, null, 3])          → [[1], [2], [3]]

Approach
Use a queue (array with push/shift) for BFS. At each level, drain exactly
queue.length nodes before moving to the next.

Sample tests

Test #1Empty input returns empty array
Input: [[]]
Output: []
Test #2Classic 3-level tree with a missing left subtree on node 20
Input: [[3,9,20,null,null,15,7]]
Output: [[3],[9,20],[15,7]]
Test #3Single-node tree
Input: [[1]]
Output: [[1]]