Blind 75 · Trees

Binary Tree Level Order Traversal

Medium

Problem

Given the root of a binary tree, return its values level by level, left to right: one inner array per depth. An empty tree yields an empty list.

Examples

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:
Input: root = [1]
Output: [[1]]

Example 3:
Input: root = []
Output: []

Example 4:
Input: root = [1,2,3,4,null,null,5]
Output: [[1],[2,3],[4,5]]

Constraints

0 <= number of nodes <= 2000
-1000 <= Node.val <= 1000

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. Breadth-First, a Level at a Time Optimal

Intuition

A queue visits nodes in level order already; the only extra requirement is knowing where one level ends. Taking the queue's size BEFORE draining it is what draws that line — everything currently queued is exactly this level, and everything added while draining is the next.

Algorithm

1. Start a queue holding the root, if there is one.
2. Note the queue's size — that is this level's width.
3. Drain exactly that many nodes into a row, enqueueing their children.
4. Repeat until the queue empties.

Time & Space

Time O(n). Space O(w) for the widest level.