The input is root, the root of a binary tree. Return its values level by level, as a list of lists: a list for each level. The levels go from the top of the tree down, and each list holds its level's values from left to right. An empty tree gives 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.
2. Each Level Built From the Last
Intuition
The same levels without counting a queue: the level being read is a list of its own, and the next one is built as a new list from its children, left before right, in order. When the new list is empty there is no level left. The first approach keeps one queue and reads its size to know where a level ends; here the two levels never share a list, so there is nothing to count. The work is the same.
Algorithm
1. Start with a list holding the root, if there is one. 2. Its values, in order, are the next row of the answer. 3. Build the next level: every child of these nodes, left before right. 4. Repeat until a level is empty.