Binary Tree Level Order Traversal

medium

Given the root of a binary tree, return the level-order traversal of its nodes' values — the values grouped level by level, from left to right, top to bottom.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Breadth-first traversal visits nodes level by level — reach for a queue.
Snapshot the queue's size before draining a level so you know exactly how many nodes belong to it.
Enqueue left before right to keep each level in left-to-right order.

Common doubts

It marks the boundary of the current level; if you read the size after enqueuing children, you'd merge two levels into one row.
Yes — recurse with a depth argument and append each value to res[depth]; recursing left-before-right keeps rows left-to-right.
An empty list [], not [[]] — there are no levels at all.

Interview follow-ups

Build the same list top-down, then reverse it (LeetCode 107).
Alternate the direction of each row — reverse every other level (LeetCode 103).

Fun facts

  • Level-order traversal is breadth-first search applied to a tree; the same queue mechanics power shortest-path BFS on graphs.
  • The queue never holds more than two adjacent levels at once, which bounds its size by the tree's maximum width.

Asked at

AmazonMicrosoftFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Level 0 is [3], level 1 is [9, 20], level 2 is [15, 7].
Example 2
Input: root = [1]
Output: [[1]]
A single node forms one level.
Example 3
Input: root = []
Output: []
An empty tree has no levels.
Constraints

- The number of nodes is in the range [0, 2000] - -1000 <= Node.val <= 1000

Solve this problem →