Binary tree level order traversal solution explained

Binary tree level order traversal is a breadth-first search with one extra habit: before processing a level, read how many nodes are in the queue, pop exactly that many, and collect their values into one list while queueing their children. Each node is enqueued and dequeued once, so it runs in O(n) time with O(w) extra memory, where w is the widest level.

By Published 7 min read

The problem, rephrased

You receive the root of a binary tree, where each node holds a value and has up to two children. Produce a list of lists. The first inner list holds the root's value, the second holds the values one step below the root, and so on down to the deepest nodes. Within each inner list, values appear from the leftmost node at that depth to the rightmost. An empty tree produces an empty list.

        8
       / \
      4   12
     /   /  \
    2   10   14
         \
          11

Output: [[8], [4, 12], [2, 10, 14], [11]]
A tree drawn for this page, and the expected output

A tree that only ever has left children, like a chain of five nodes, produces five lists with one value each. A single node produces one list with one value. Ask how the tree is given to you, as node objects or as an array, and whether the interviewer wants the levels top-down or bottom-up.

Why interviewers reach for it

This problem checks one thing directly: do you know breadth-first search well enough to control it? Plain BFS visits nodes in the right order, but it loses track of where one level ends and the next begins. Interviewers watch for the snapshot of the queue size at the start of each level, and many follow with a variant to see if you can adapt the loop without rewriting it.

  • Zigzag order. Reverse every second level, or fill each level's list from alternating ends with a deque.
  • Bottom-up order. Build the levels as usual and reverse the outer list once at the end.
  • Right side view. Keep only the last value of each level.
  • Average or maximum per level. Replace the list with a running sum or a running maximum.
  • Minimum depth. Stop the search at the first leaf you dequeue, which BFS reaches before any deeper node.
  • N-ary trees. Loop over a list of children instead of left and right. Nothing else changes.

A slow way that still works

Find the tree's height h first. Then, for each depth d from 0 to h minus 1, walk the tree from the root and collect the nodes found at exactly depth d, visiting left before right. Each walk can touch most of the tree, so the cost is O(n·h). On a balanced tree that is O(n log n), and on a one-sided chain it becomes O(n²). It also recurses, so a deep chain can hit the recursion limit. It is worth a sentence; the next idea is to never revisit a node.

Breadth-first search, one level at a time

Put the root in a queue. While the queue is not empty, record its current length; that number is exactly how many nodes belong to the level you are about to read, because the previous round added all of them and nothing else. Pop that many nodes, append each value to a fresh list, and push each node's left child and then its right child. When the inner loop ends, the fresh list is complete, so append it to the result.

from collections import deque


class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def levels_of(root):
    if root is None:
        return []
    result = []
    queue = deque([root])
    while queue:
        row = []
        for _ in range(len(queue)):  # exactly the nodes of this level
            node = queue.popleft()
            row.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        result.append(row)
    return result
Python: a deque, so popping from the front is O(1). O(n) time, O(w) extra space.
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function levelsOf(root) {
  const result = [];
  let current = root ? [root] : [];
  while (current.length > 0) {
    const next = [];
    result.push(current.map((node) => node.val));
    for (const node of current) {
      if (node.left) next.push(node.left);
      if (node.right) next.push(node.right);
    }
    current = next;
  }
  return result;
}
JavaScript: one array per level instead of shift(), which can be O(n) per call.

The JavaScript version swaps the single queue for two arrays: the current level and the next one. That sidesteps shift(), which in many engines moves every remaining element, and it makes the level boundary obvious without counting.

The depth-first alternative

A depth-first walk can build the same output if it carries the depth along. Visit left before right; when you reach a depth for the first time, add a new empty list; then append the value to the list at that depth. Pre-order with left first guarantees that values at each depth arrive in left-to-right order. Memory is O(h) for the call stack, which is good on a wide, shallow tree and risky on a very deep one.

def levels_by_depth(root):
    result = []

    def visit(node, depth):
        if node is None:
            return
        if depth == len(result):
            result.append([])
        result[depth].append(node.val)
        visit(node.left, depth + 1)
        visit(node.right, depth + 1)

    visit(root, 0)
    return result
Python: depth-first, passing the depth. O(n) time, O(h) stack.

Complexity

n nodes, height h, widest level w
ApproachTimeExtra space beyond the output
One walk from the root per depthO(n·h), O(n²) when the tree is a chainO(h) for recursion
BFS with a queue, level by levelO(n)O(w), up to about n/2 for a full bottom level
DFS carrying the depthO(n)O(h) for recursion
n nodes, height h, widest level w. Scroll sideways on a small screen.

Which extra-space figure is better depends on the tree's shape. A complete tree is wide at the bottom and shallow, so DFS uses less memory. A long chain is narrow and deep, so BFS uses less and also avoids any recursion limit.

Cases to check

  • An empty tree should give an empty list, not a list containing one empty list.
  • A single node.
  • A tree that leans entirely to one side, where each level has one value.
  • A level where only the right child exists, as with node 10 in the example above.
  • Duplicate values, which matter only if your code uses values as keys anywhere. It should not.
  • A deep chain of thousands of nodes, which tests whether the recursive versions survive.

Where people slip

  • Using the live queue length as the loop condition, so children added during the level are read as part of it.
  • Calling pop(0) on a Python list or shift() on a JavaScript array and still claiming O(n) overall.
  • Pushing null children and then reading .val from them.
  • Pushing the right child before the left one, which reverses each level.
  • Returning [[]] for an empty tree.

Explaining it clearly

Fictional example

A concise spoken version
Candidate
Breadth-first search already visits nodes level by level. The only thing it does not do is tell me where a level ends.
Candidate
So at the start of each round I read the queue's size. Those are exactly this level's nodes, because the previous round added all of them. I pop that many, collect their values, and queue their children for the next round.
Candidate
Each node goes in and out of the queue once, so it is linear time, and the queue never holds more than the widest level plus its children.

More problems from this set

The grid version of this same queue is Number of Islands, where breadth-first search marks every cell of an island. The stack that replaces the queue in depth-first search is the star of Valid Parentheses. If you started here, Two Sum is the gentlest warm-up, and the coding problems hub lists every walkthrough.

Practice support from Natively

Tree problems are often shown as a drawing, which makes a screenshot the quickest way in. During practice, Natively can read a tree problem from your screen on Mac or Windows, suggest breadth-first or depth-first search, and note the cases that trip people up, such as the empty tree. It also transcribes your mock interview so you can review how you explained the level boundary. See the AI interview assistant.

Questions people ask

How do you do a level order traversal of a binary tree?

Use a queue. At the start of each round, read the queue's size, pop exactly that many nodes into one list, and enqueue their children. Each round produces one level.

What is the time and space complexity of level order traversal?

O(n) time, since each node enters and leaves the queue once, and O(w) extra space, where w is the widest level of the tree.

Can level order traversal be done with DFS?

Yes. Pass the depth into a recursive walk that visits the left child before the right, and append each value to the list for its depth. It uses O(h) stack space instead of a queue.

What variants of level order traversal are asked?

Zigzag order, bottom-up order, the right side view, averages or maximums per level, and minimum depth. All are small changes to the same loop.

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