TRT
Sign in
mediumCoreLeetCode#breadth-first search#level size snapshot

Binary tree level order traversal

Return a tree's values level by level, using a queue and the length of the queue at the start of each level.

The Runtime Theory Team1 min read
Taught inLevel-order traversalPro — members onlyVisiting a tree level by level needs a queue instead of a stack. Taking a snapshot of the queue's size separates one level from the next, which solves a family of problems about depth, width and views.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

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

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

inroot = [1]

out[[1]]

inroot = []

out[]

Given the root of a binary tree, return its values level by level, from left to right within each level.

Before you code

A queue gives nodes in level order, but the answer also needs to know where each level ends. The queue's length at the start of a round is exactly the size of one level.

Hints

  1. Start the queue with the root, if there is one.
  2. Each round: read len(q), dequeue exactly that many nodes, collect their values and enqueue their children.
  3. Use a real queue (collections.deque), not list.pop(0).

Production & complexity notes

When solving Binary tree level order traversal on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Level-order traversal to reinforce the underlying pattern.

What it practices

Processing one level at a time, from Level-order traversal.

Not started

Sign in to save your learning progress.

Sign in to save