Skip to content
Problem 429 · LeetCode 429(opens in a new tab)

N-ary Tree Level Order Traversal

MediumBreadth-first search

You are given the root of an n-ary tree: each node has a value and a list of children, in order, with no limit on how many. Return the values level by level: one list for the root, one for its children, one for their children, and so on. Within a level, list the values from left to right.

In the examples, a tree is written in level order. Each group of children follows its parent's group, and null closes a group, so [7, null, 2, 9, 4] is 7 with children 2, 9 and 4.

Example 1

Input:  root = [7, null, 2, 9, 4, null, 1, null, null, 5, 6]
Output: [[7], [2, 9, 4], [1, 5, 6]]
Why:    1 is under 2, 9 has no children, 5 and 6 are under 4
2 more examples and the constraints

Example 2

Input:  root = []
Output: []
Why:    an empty tree has no levels

Example 3

Input:  root = [3, null, 8, null, 1]
Output: [[3], [8], [1]]
Why:    a chain has one node per level

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • The tree is at most 1,000 levels tall

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS with a depth counterO(n)
  2. BFS, one level per roundO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
DFS with a depth counterO(n)
Passes; recursion as deep as the tree
BFS, one level per roundO(n)
Best; no recursion, the natural fit

n = nodes, h = height, w = widest level. Both visit every node once.

Edge cases to test

  • Empty tree. Return an empty list, not [[]].
  • One node. The answer is a single row with the root's value.
  • A tall chain. 1,000 levels of one node each: deep recursion, tiny queue.
  • A node with no children. In Example 1, 9 adds nothing to the queue, but its level still ends after 4.

Common mistakes

  • Popping until the queue is empty in one round, which mixes several levels into one row.
  • Returning [[]] for an empty tree.
  • Putting every node in one flat list and losing where each level starts.

How to talk through it

  1. 1Clarify. Can the tree be empty? Should each level read left to right? How tall can it get?
  2. 2Pick BFS. The answer is grouped by depth, and BFS visits nodes in order of depth.
  3. 3Find the level boundary. Read the queue size at the start of a round; that many pops make one row.
  4. 4Mention the DFS. Passing the depth down also works, but the recursion can be 1,000 calls deep.
  5. 5Test out loud. Run an empty tree, one node and a node with no children in the middle of a level.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?