349. N-ary Tree Level Order Traversal
You are given the root of an n-ary tree: every node stores an integer val and a list children holding any number of child nodes (possibly none). Nothing limits how many children a node may have.
Group the node values by depth and return the groups as a list of lists, shallowest level first. The first group contains just the root's value; the second contains the values of all depth-1 nodes in left-to-right order; and so on down to the deepest level. Within a level, values must appear in the same left-to-right order as the nodes themselves.
Example 1:
Input: root = [1, null, 3, 2, 4, null, 5, 6]
Output: [[1], [3, 2, 4], [5, 6]]
Explanation: The root 1 sits alone on level 0. Its children 3, 2, 4 form level 1, and node 3's children 5, 6 form level 2.
Example 2:
Input: root = [10, null, 20, 30, 40, null, 50, 60, null, null, 70]
Output: [[10], [20, 30, 40], [50, 60, 70]]
Explanation: Level 2 gathers children across different parents: 50 and 60 belong to node 20, while 70 belongs to node 40 — left-to-right order is preserved.
Constraints:
- 1 ≤ total number of nodes ≤ 10⁴
- -10⁴ ≤ Node.val ≤ 10⁴
- The height of the tree does not exceed 1000.
Hints:
Think in rings: if you already hold every node of depth d, then the concatenation of their children lists — in that exact order — is every node of depth d+1.
A queue makes the ring precise. Snapshot the queue's size at the start of a round: exactly that many pops belong to the current level; push each popped node's children so the next round is the next level.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: root = [1, null, 3, 2, 4, null, 5, 6]
Expected output: [[1], [3, 2, 4], [5, 6]]