Skip to content
Optimal Lab

Trees · 028Medium

Binary Tree Level Order Traversal

Given the root of a binary tree, return its level-order traversal: the node values grouped level by level, from left to right.

Constraints

  • The tree holds 0 to 2000 nodes.
  • -1000 <= Node.val <= 1000
  • INPUT FORMAT
  • `root` is a TreeNode object, not an array. The arrays in EXAMPLES are the level-order
  • serialization the platforms print — breadth-first, with `null` for a missing child. The
  • test runner builds a real tree from that array before calling your function.

Examples

levelOrder([3, 9, 20, null, null, 15, 7])  ->  [[3], [9, 20], [15, 7]]
levelOrder([1])                            ->  [[1]]
levelOrder(null)                           ->  []
levelOrder([1, 2, 3, 4, 5, 6, 7])          ->  [[1], [2, 3], [4, 5, 6, 7]]  // perfectly balanced
levelOrder([1, null, 2, null, 3])          ->  [[1], [2], [3]]  // skewed: one node per level
levelOrder([-1, -2, -3])                   ->  [[-1], [-2, -3]]  // negatives

Edge cases

  • Empty tree returns an empty array.
  • Null children must not be enqueued.
Show the target complexity (spoiler)
Naive
O(n * h) time — repeatedly walk the tree collecting one depth at a time.
Target
O(n) time, O(n) space — a BFS queue, processing exactly one level per outer iteration.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/07-trees/028-binary-tree-level-order-traversal.js
./practice c 028

Stuck? Watch the pattern run