107/670

107. Binary Tree Level Order Traversal II

Medium

You are handed the root of a binary tree. Group its values by depth — every node the same distance from the root lands in one group, ordered left to right — and return the list of groups starting with the deepest level and ending with the root's level.

In other words, run the familiar top-down breadth-first walk, then hand the levels back upside down.

An empty tree produces no groups at all.

Levels are collected top-down, returned bottom-up
3920157returned order[3]last[9, 20][15, 7]first

Example 1:

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

Output: [[15, 7], [9, 20], [3]]

Explanation: The tree has three levels. Deepest first gives [15, 7], then [9, 20], and the root level [3] comes last.

Example 2:

Input: root = [1]

Output: [[1]]

Explanation: A single node is its own (and only) level.

Constraints:

  • 0 ≤ number of nodes ≤ 2000
  • -1000 ≤ node value ≤ 1000

Hints:

A queue gives you the standard top-down walk: repeatedly drain everything currently in the queue (one full level) while enqueueing those nodes' children for the next round.

Once the levels are collected top-down, the answer is just that list reversed — or, equivalently, insert each finished level at the front as you go.

A recursive version works too: pass the depth down, append `node.val` to `levels[depth]` (creating the group the first time that depth appears), and flip the list at the end.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: [[15, 7], [9, 20], [3]]