Skip to content

Binary Tree Level Order Traversal

List a binary tree's values level by level, left to right, by processing a BFS queue in batches.

MediumTree BFS
Solve on LeetCode

The problem

You get the root of a binary tree. Return the values of its nodes level by level: one list per level, from the root's level down, with the values inside each level ordered from left to right.

Input root = [7, 2, 9, 1, null, 8, 11]

Output [[7], [2, 9], [1, 8, 11]]

The first level is the root, the second holds its children 2 and 9, and the third holds 1, 8 and 11.

Input root = [4, null, 6, 5]

Output [[4], [6], [5]]

Missing children just don't appear, so each of these levels has a single value.

Key constraint: Each level must come out as its own list, so you need to know where one level ends and the next one starts.

How to spot the pattern

  • The output is grouped by depth.
  • Left-to-right order inside a level is exactly the order in which a queue hands out nodes.

The idea

A queue gives nodes back in the order they were discovered, which for a tree means level by level, left to right. To split the output into levels, process the queue in batches: before each batch the queue holds exactly one level, so its current size tells you how many nodes to pop for this level, while their children line up behind them for the next one.

Brute force: For each depth from 0 to the height, walk the tree from the root and collect the nodes at that depth, which costs O(n * h) time.

Step by step

  1. 1If the root is null, return an empty list; otherwise put the root in a queue.
  2. 2While the queue is not empty, read its size size.
  3. 3Pop size nodes, append their values to a new list for this level, and push their left and right children when they exist.
  4. 4Add the level's list to the answer, and return the answer when the queue is empty.

See the pattern move

The tree bfs pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if root is None:
            return []
        levels = []
        queue = deque([root])
        while queue:
            level = []
            for _ in range(len(queue)):  # exactly the nodes of one level
                node = queue.popleft()
                level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            levels.append(level)
        return levels

Complexity

Time

O(n)

Space

O(n)

Every node enters and leaves the queue once; the queue holds at most one level plus its children, and the answer stores all n values.

Watch out for

  • Using the queue's size inside the loop while you are pushing children, so it keeps changing; read it once before the batch.
  • Pushing null children into the queue and then reading .val from them.
  • In Python, using a list with pop(0), which is O(n) per pop; use collections.deque.

Follow-up questions

Can you return the levels from the bottom up?

Collect them exactly the same way, then reverse the list of levels at the end. That is Level Order Traversal II.

Can you do it with DFS?

Yes: pass the depth down and append each value to levels[depth], creating that list the first time you reach a new depth. Visiting the left child before the right one keeps the left-to-right order.

In Hinglish

Queue ka size dekho, utne hi nodes is level ke hain. Unhe nikaalo, values ek list mein daalo, aur bacchon ko agle level ke liye queue mein bhejo.

Related problems