Binary Tree Level Order Traversal

Medium Solved

Description

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).

Input format / Clarification (important):

To make the web runner simple, the tree is provided as a single JSON array representing the level-order (breadth-first) serialization where null marks missing children. This is the same format commonly used on LeetCode and similar platforms.

Example representation: [3,9,20,null,null,15,7] corresponds to the tree:

      3
     / \
    9  20
      /  \
     15   7
          

Output should be a JSON array of arrays, one inner array per level. For the example above output: [[3],[9,20],[15,7]].

Algorithm hint:

Use a queue (BFS) to traverse the tree level by level. For each level, collect node values and append the list to the result. Watch out for null placeholders in the input array.

Examples

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

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

Input: [1]

Output: [[1]]

Input: [] (empty tree)

Output: []

Note:

The runner reads one line from stdin: the JSON array representing the tree. Your program must print the final result as a JSON array (string) so it can be compared with expected output.

Your Submissions

No submissions yet.

Discuss

Compare BFS vs recursive approaches that build level arrays (depth tracking). Discuss handling of null placeholders and sparse trees.

Test Cases

Test Case 1
Test Case 2
Test Case 3