N-ary Tree

N-ary Tree Level Order Traversal

Medium
Solve it on LeetCode ↗

The problem

Return the values of an n-ary tree grouped level by level, top to bottom.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Start with the root in a queue (empty tree → empty result).
  2. 2While the queue is non-empty: record its current size s, pop exactly s nodes, collecting values into one level array.
  3. 3Enqueue all children of each popped node.
  4. 4Push the level array into the result.

Key insight

Freezing the queue size before draining a level is the universal "group BFS by depth" trick — it works unchanged for any branching factor.

The solution

Watch out for

  • Reading len(queue) inside the drain loop (instead of freezing it) merges levels.
  • Children lists can be null in some codebases — guard with a default empty list.