All coding questions

Binary Tree Level Order Traversal

medium
NeetCode 150treesbfs

Problem

Given the root of a binary tree, return its node values grouped level by level from top to bottom, each level read left to right.

Examples

Input: [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Each inner list is one level.

Constraints

  • 0 <= number of nodes <= 2000
  • -1000 <= node value <= 1000
Hints(tap to reveal)
  • 1. A queue processes nodes breadth first.
  • 2. Process one full level at a time by tracking the queue size.
Optimal approach(spoiler)
  1. Seed a queue with the root if it exists.
  2. For each level, record the current queue size as the level width.
  3. Dequeue exactly that many nodes, collecting their values and enqueuing children.
  4. Append the collected values as one level.
  5. O(n) time, O(n) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor