N-ary Tree Level Order Traversal solution explained

To do an N-ary tree level order traversal, run a breadth-first search and process the tree one level at a time: take every node currently in the queue, record its value, and queue all of its children for the next round. Each finished round is one list in the answer. Every node is enqueued once, so the traversal is O(n) time with O(w) extra space, where w is the widest level.

By Published 8 min read

The task in our words

Every node in the tree stores a value and an ordered list of children. The list might be empty for a leaf, or have one, five or a thousand entries. Return a list of lists: the first holds the root's value, the second holds the values of the root's children in order, the third holds the grandchildren, and so on. Inside a level, nodes appear left to right, which means a node's children come before the children of the next node at the same depth.

              8
        /   /   \   \
       3   11    6   1
      / \        |
     4   9       2
                 |
                 7

Answer: [[8], [3, 11, 6, 1], [4, 9, 2], [7]]
A tree made up for this page

Note that 2 sits under 6, which is the third child of the root, yet it lands in the same list as 4 and 9 because all three are two edges below the root. The order within that list is 4, 9, 2 because 3 comes before 6 among the root's children. An empty tree returns an empty list, not a list holding an empty list.

How it differs from the binary version

The algorithm is the same breadth-first search as Binary Tree Level Order Traversal. What changes is the inner step. Instead of checking a left and a right pointer, you loop over a children list, and that list can be long. Two consequences follow. First, the widest level can be far wider than in a binary tree of the same height: a root with 100,000 leaf children puts all of them in one level, so memory is driven by width, not depth. Second, the input format on judge sites for N-ary trees is often a flat list with separators between child groups, and some candidates lose time parsing it. In an interview you can usually assume the tree is already built, but say so.

Interviewers use the problem as a warm-up, then stretch it. Typical stretches:

  • Right side view. Return the last value of each level. Only the final node of each round matters.
  • Level averages or level maxima. Same rounds, a different reduction per round.
  • Alternate direction each level. Reverse every other list after building it; do not try to reverse the queue.
  • Serialize and rebuild the tree. Level order plus a marker after each node's children is one common format.
  • Find the deepest level's leftmost value. The first entry of the last round.

Naive version: one scan per depth

Without a queue, you could ask a simpler question many times: which nodes sit at depth d? A depth-limited walk from the root answers it, collecting nodes when the current depth equals d and not going deeper. Do that for d = 0, 1, 2 and so on until a scan finds nothing. It is correct, and the order comes out left to right because the walk visits children in order. The cost is the problem: the scan for depth d touches every node above it, so a tree of height h costs up to O(n·h), which is O(n²) for a chain.

class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children if children is not None else []

def level_order_by_depth_scan(root):
    result = []
    depth = 0
    while True:
        row = []

        def collect(node, d):
            if d == depth:
                row.append(node.val)
                return
            for child in node.children:
                collect(child, d + 1)

        if root is not None:
            collect(root, 0)
        if not row:
            return result
        result.append(row)
        depth += 1
Python: rescan the tree for each depth. Correct, O(n·h). Our test reference.

The standard answer: breadth-first, a round at a time

A queue visits nodes in exactly the order you want: all of depth 0, then all of depth 1, and so on. The only extra work is knowing where one level ends. The usual trick is to read the queue's length at the start of a round. Those many nodes are the current level; pop exactly that many, record their values, and push their children, which belong to the next round. When the queue is empty, you are done.

from collections import deque

def level_order(root):
    if root is None:
        return []
    result = []
    queue = deque([root])
    while queue:
        row = []
        for _ in range(len(queue)):
            node = queue.popleft()
            row.append(node.val)
            queue.extend(node.children)
        result.append(row)
    return result
Python: BFS with a deque, level boundary from the queue length. O(n) time, O(w) space.

In JavaScript, Array.prototype.shift removes the first element and moves the rest down. Engines optimize small arrays, but large ones can pay for every move: in a quick test on Node, emptying a 100,000-item array with shift took several seconds, while 10,000 items took under a millisecond. Swapping two plain arrays avoids the issue: the current frontier is read front to back, children go into a fresh array, and that array becomes the next frontier.

function levelOrder(root) {
  const result = [];
  let frontier = root === null ? [] : [root];
  while (frontier.length > 0) {
    const values = [];
    const next = [];
    for (const node of frontier) {
      values.push(node.val);
      for (const child of node.children) next.push(child);
    }
    result.push(values);
    frontier = next;
  }
  return result;
}
JavaScript: frontier arrays instead of a shifting queue. O(n) time.

A depth-first alternative

Level order does not strictly require a queue. If a pre-order walk carries the depth, it can append each value to result[depth], creating that list the first time the depth is reached. Because the walk visits a node's children left to right before moving on, every level's list fills in left-to-right order. It is O(n) as well, with O(h) stack instead of O(w) queue, which wins on very wide, shallow trees and loses on deep chains, where Python's recursion limit of about a thousand frames gets in the way.

def level_order_dfs(root):
    result = []

    def visit(node, depth):
        if depth == len(result):
            result.append([])
        result[depth].append(node.val)
        for child in node.children:
            visit(child, depth + 1)

    if root is not None:
        visit(root, 0)
    return result
Python: pre-order DFS that appends to result[depth]. O(n) time, O(h) stack.

Complexity

n nodes, height h, widest level w
ApproachTimeExtra space (besides the output)
Rescan per depthO(n·h)O(h) stack per scan
BFS with a deque and level sizeO(n)O(w)
BFS with frontier arraysO(n)O(w) for two arrays
BFS on a large JavaScript array with shift()Can degrade toward O(n·w)O(w)
DFS appending to result[depth]O(n)O(h) stack
n nodes, height h, widest level w. Scroll sideways on a small screen.

Cases worth running

  • Empty tree: [] rather than [[]].
  • Single node: one list with one value.
  • A wide star: two levels, the second very long; this is where shift() hurts.
  • A chain: one value per level; this is where recursion hurts.
  • Uneven depths, like the example, where a later sibling's child joins an earlier sibling's children in one list.
  • Repeated values: the output lists values, not unique values, so duplicates stay.

Where answers go wrong

  • Reading len(queue) inside the loop condition instead of once per round, which mixes levels.
  • Pushing the children list itself rather than its elements, so the queue holds lists.
  • Starting a new row for every node instead of every round.
  • Using shift() on a large JavaScript array without mentioning its cost.
  • Returning [[]] for an empty tree because the loop runs once before checking.

Saying it in the interview

Fictional example

A short, complete explanation
Candidate
Level order is breadth-first search. The only question is where each level ends, so at the top of every round I read how many nodes are in the queue and process exactly that many.
Candidate
For each one I record the value and push all its children. They are behind the current level in the queue, so they form the next round.
Interviewer
Anything to watch in JavaScript?
Candidate
Shift is linear, so on a wide level I would swap two arrays instead. Each node is still handled once, so it is O(n) time and memory peaks at the widest level.

Once level order is comfortable, Diameter of N-ary Tree uses the same node shape for a depth-first problem. Find Duplicate Subtrees asks you to describe whole subtrees rather than levels, and Number of Closed Islands applies the same queue to a grid. The Number of Islands walkthrough is the grid version of breadth-first search from scratch.

Where Natively can help

For practice on Mac or Windows, Natively can read a traversal problem from a screenshot and put an approach and code in its overlay, which is handy when you want to compare your queue version with a depth-first one. It can also transcribe you while you explain the solution aloud, so you can reread whether you mentioned the level boundary and the shift cost. More on using an AI interview assistant.

Questions people ask

How do you do a level order traversal of an N-ary tree?

Use breadth-first search. At the start of each round, read how many nodes are queued, process exactly that many, record their values as one list, and queue all of their children for the next round.

How is N-ary level order different from binary tree level order?

The algorithm is the same, but each node has a list of children instead of a left and right pointer, so you loop over the list. Levels can also be much wider.

What is the time complexity of N-ary Tree Level Order Traversal?

O(n) time, since each node is queued and removed once, and O(w) extra space, where w is the number of nodes in the widest level.

Can you do N-ary level order traversal with DFS?

Yes. A pre-order walk that carries the depth can append each value to result[depth]. It is also O(n), uses O(h) stack, and keeps left-to-right order.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP