102. Binary Tree Level Order Traversal
Your function receives the root of a binary tree (possibly empty; each node exposes val, left, and right). Walk the tree one level at a time, from the root down, and return a list of levels: the first inner list holds the root's value, the second holds the values of depth 1 from left to right, and so on.
So for a tree whose root is 3 with children 9 and 20, and where 20 has children 15 and 7, the answer is [[3], [9, 20], [15, 7]].
Return an empty list for an empty tree. Within every level the order must be left to right.
Example 1:
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Explanation: Depth 0 holds just the root 3, depth 1 holds 9 and 20 (left to right), and depth 2 holds 20's children 15 and 7.
Example 2:
Input: root = [1]
Output: [[1]]
Explanation: A single node is a single one-element level.
Constraints:
- 0 ≤ number of nodes ≤ 2000
- -1000 ≤ Node.val ≤ 1000
Hints:
You need to know which depth each value belongs to. What data structure hands nodes back in exactly the order they were discovered?
Push the root into a queue. Snapshot the queue's current size — that is one whole level — pop exactly that many nodes, record their values, and enqueue their children. Repeat until the queue drains.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: root = [3, 9, 20, null, null, 15, 7]
Expected output: [[3], [9, 20], [15, 7]]