15% off all plans & roadmaps Use code

See plans

Binary Tree Level Order Traversal

Updated

TL;DR: Return a binary tree's values grouped by depth, left to right. Run a breadth-first search with a queue, and read the queue size at the start of each round to know how many nodes belong to the current level.

Problem

Given the root of a binary tree, return the level order traversal of its node values. That means you list the values from left to right, one level at a time, and return them as a list of lists.

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2

Input: root = [1]
Output: [[1]]

Example 3

Input: root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Constraints that matter

  • Up to 2000 nodes means even an O(n * h) solution runs in about 4 million steps, so the slow approach is correct here. It is still the wrong answer in an interview, because the linear solution is as short.
  • The node count can be 0, so root can be null. You must return an empty list instead of a list holding an empty list.
  • A tree of 2000 nodes can be a single chain of depth 2000. Recursive solutions need that much stack, which exceeds Python's default recursion limit of 1000.
  • Values between -1000 and 1000 cause no overflow or precision trouble. Values are only copied, never combined, so the value range does not affect the algorithm.

View on LeetCode

Hints

Hint 1

This is a level order traversal, which is breadth-first search (BFS) on a tree.

Hint 2

Find the height h of the tree.

Solution

Intuition

This is a level order traversal, which is breadth-first search (BFS) on a tree. BFS visits every node at depth d before any node at depth d + 1. That is the order the output asks for, so the remaining job is to cut the visiting order into groups.

Picture a checkout line where each person who finishes an errand rejoins the back of the line. At the start of each round you count the people standing there, serve exactly that many, and the people who rejoin during that round form the next group.

A queue gives you the visiting order. You push the root, and every time you pop a node you push its left child and then its right child. Children always go behind everything already waiting, so nodes leave the queue in order of depth, and left to right within a depth.

The grouping comes from one observation. When a round begins, the queue holds all nodes of one level and nothing else. Read len(queue) right then and call it k. Pop exactly k nodes, and those are the whole level. The children you push during those pops wait behind them for the next round.

A second route reaches the same output without a queue. In a depth-first search you pass the depth along, and you append each node's value to the list for its depth. Left subtrees are visited before right subtrees, so each level's list fills left to right. Both routes touch each node once. The BFS version avoids deep recursion, which is why it is the one to memorise.

Watch the pattern animation

Worked example

Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Explanation: The root 3 is alone on level 0. Its children 9 and 20 form level 1, read left to right. Node 20 has children 15 and 7, which form level 2. Nodes 9, 15 and 7 are leaves, so nothing lies below level 2.

Approach 1: Brute force: one traversal per level

Find the height h of the tree. Then, for each level number from 0 to h - 1, start at the root and walk down the tree, collecting only the nodes whose depth equals that level. Each pass produces one inner list.

This is correct and needs no queue or clever bookkeeping. It is also the version a beginner writes when asked for the nodes of one level and then told to repeat it for every level.

Steps

  1. Compute the height of the tree with a recursive helper: 0 for null, otherwise 1 plus the larger child height.
  2. Create an empty result list.
  3. For each level from 0 up to height - 1, create an empty list for that level.
  4. Run a DFS from the root that tracks the current depth. When the depth equals the target level, append the node's value and stop descending. Otherwise recurse into the left child, then the right child.
  5. Append the level's list to the result.
  6. Return the result.

Dry run

The tree has height 3 (levels 0, 1, 2).

  • Level 0: the DFS starts at 3 with depth 0, which matches the target. It appends 3. Result so far: [[3]].
  • Level 1: the DFS enters 3 at depth 0, which does not match. It goes left to 9 at depth 1 and appends 9. It goes right to 20 at depth 1 and appends 20. Result: [[3],[9,20]].
  • Level 2: the DFS walks 3, then 9 (children are null), then 20, then 15 and 7 at depth 2. It appends 15 and 7. Result: [[3],[9,20],[15,7]].

The pass for level 2 visits five real nodes, the pass for level 1 visits three, and the pass for level 0 visits one. The same upper nodes are walked again for every level. The final result matches the expected output.

Complexity

TimeO(n * h), which is O(n^2) in the worst case
SpaceO(h) extra, plus the output

Here n is the number of nodes and h is the height. Each of the h level passes can visit up to n nodes, and the height computation adds one more O(n) pass, giving O(n * h). A chain has h = n, so the worst case is O(n^2). Apart from the output, the only extra memory is the recursion stack, which is at most h frames deep.

PythonTested in our runner

import sys
from typing import List, Optional

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        sys.setrecursionlimit(10000)  # a chain of 2000 nodes needs deep recursion

        def height(node):
            if not node:
                return 0
            return 1 + max(height(node.left), height(node.right))

        def collect(node, depth, target, out):
            if not node:
                return
            if depth == target:
                out.append(node.val)
                return
            collect(node.left, depth + 1, target, out)
            collect(node.right, depth + 1, target, out)

        result = []
        for level in range(height(root)):
            out = []
            collect(root, 0, level, out)
            result.append(out)
        return result

Approach 2: DFS with a depth index

What's slow: the brute force walks the upper levels again for every deeper level, and it needs a separate height pass. Each node is reached h times in the worst case when it only needs to be handled once.

The insight that fixes it: a single DFS can carry the depth with it. When you reach a node at depth d, append its value to the list for level d, creating that list if this is the first node seen at that depth. Visit the left child before the right child, and each level's list fills in left to right order.

Steps

  1. Create an empty result list of lists.
  2. Define dfs(node, depth). If the node is null, return.
  3. If depth equals the current length of the result, append a new empty list, because this is the first node found at that depth.
  4. Append the node's value to result[depth].
  5. Call dfs on the left child with depth + 1, then on the right child with depth + 1.
  6. Call dfs(root, 0) and return the result.

Dry run

Start with result = [].

  • dfs(3, 0): depth 0 equals the length 0, so add a new list. result = [[3]].
  • dfs(9, 1): depth 1 equals the length 1, so add a list. result = [[3],[9]]. Both children of 9 are null and return at once.
  • dfs(20, 1): the list for depth 1 already exists. result = [[3],[9,20]].
  • dfs(15, 2): depth 2 equals the length 2, so add a list. result = [[3],[9,20],[15]].
  • dfs(7, 2): the list exists, so append. result = [[3],[9,20],[15,7]].

The tree was walked once, and the output matches the expected answer.

Complexity

TimeO(n)
SpaceO(h) for the call stack, plus the output

Here n is the number of nodes and h is the height. Each node is passed to dfs exactly once, and each null child adds one call that returns immediately, so there are at most 2n + 1 calls and each does O(1) work. The recursion stack holds at most h frames, which is O(n) for a chain and O(log n) for a balanced tree. The output holds n values.

PythonTested in our runner

import sys
from typing import List, Optional

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        sys.setrecursionlimit(10000)  # a chain of 2000 nodes needs deep recursion
        result = []

        def dfs(node, depth):
            if not node:
                return
            if depth == len(result):
                result.append([])  # first node seen at this depth
            result[depth].append(node.val)
            dfs(node.left, depth + 1)
            dfs(node.right, depth + 1)

        dfs(root, 0)
        return result
Level Order Traversal pattern infographic for Binary Tree Level Order Traversal

Solution pattern

Level Order Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 3: BFS with a queue and level sizeOptimalLevel Order Traversal

What's slow: the DFS is linear, but it recurses as deep as the tree and builds levels out of order, jumping between lists as it goes. A chain of 2000 nodes also overflows Python's default recursion limit. Its traversal order is not the order the problem asks for.

The insight that fixes it: breadth-first search already visits nodes level by level, so use it directly. Keep a FIFO queue. At the start of each round the queue holds exactly one level, so read its size k.

Pop k nodes into one list, pushing each node's left and right children as you go. Those children queue up behind the current level and form the next round.

Why it is correct. Claim: at the start of every round, the queue holds exactly the nodes of one depth, in left-to-right order. It holds initially, since only the root is there. Popping a level and pushing its children adds exactly the next depth behind it, so the claim holds for the next round. Because k is read before any pops, the group size is exactly that level's node count.

Steps

  1. If root is null, return an empty list.
  2. Create a queue holding root, and an empty result list.
  3. While the queue is not empty, store k = len(queue) before touching the queue.
  4. Create an empty list level, then repeat k times: pop the front node, append its value to level.
  5. After each pop, push the node's left child if it exists, then its right child if it exists.
  6. After k pops, append level to the result.
  7. When the queue empties, return the result.

Dry run

Each row below is one round of the outer loop, with the queue shown as it was at the start of that round.

RoundQueue at startkPops (value, children pushed)levelresult after round
1[3]13 pushes 9, 20[3][[3]]
2[9, 20]29 pushes nothing; 20 pushes 15, 7[9, 20][[3], [9, 20]]
3[15, 7]215 pushes nothing; 7 pushes nothing[15, 7][[3], [9, 20], [15, 7]]
end[]-loop stops-[[3], [9, 20], [15, 7]]

In round 2 the queue grows from 2 to 2 entries (9 and 20 leave, 15 and 7 arrive), yet the loop still pops exactly 2 times because k was fixed at the start. The final result is [[3],[9,20],[15,7]], the expected output.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of nodes. Every node is pushed once and popped once, and each push, pop and append costs O(1), so the total work is O(n). The queue holds at most two adjacent levels' worth of nodes at a time, and a single level can contain about n / 2 nodes in a complete tree, so the queue is O(n). The output also stores n values.

The queue never grows with the tree's depth, so a chain of 2000 nodes uses only O(1) queue space.

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        result = []
        if not root:
            return result

        queue = deque([root])
        while queue:
            level = []
            # range(len(queue)) is evaluated once, so it fixes the level size
            for _ in range(len(queue)):
                node = queue.popleft()
                level.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(level)
        return result

Common mistakes

  • Writing the inner loop as while i < queue.size() in Java or C++. The size grows as you push children, so levels merge. Store size = queue.size() in a variable before the inner loop.
  • Pushing null children, as in queue.offer(node.left) with no check. The next pop returns null and node.val throws. Guard each push with if (node.left != null).
  • Skipping the empty-tree check. With root = null, queue.offer(root) puts a null in the queue, and the first pop crashes. Return an empty list before building the queue.
  • Using list.pop(0) as the queue in Python. Each call shifts the whole list, which costs O(n). Use collections.deque and popleft().
  • In the DFS version, appending to result[depth] before checking depth == len(result). The first node at a new depth raises an index error. Create the empty list first when depth equals the length.
  • Reusing one level list across rounds, for example calling level.clear() after result.append(level) in a language that stores references. Every stored level ends up empty. Create a fresh list each round.

Edge cases

  • root = [] (null root): return [], not [[]].
  • A single node [1]: return [[1]], one round with k = 1.
  • A left-only chain of 2000 nodes: output is 2000 lists of one value each. The BFS queue stays at size 1, but the recursive approaches need a stack 2000 deep.
  • A right-only chain: each level holds one node, and the traversal must still push the right child when the left is null.
  • A complete tree such as 7 nodes in 3 levels: output sizes 1, 2, 4. The queue peaks at 4 entries, which shows the O(n) space.
  • Duplicate and negative values such as [-1, -1, -1]: the traversal uses nodes, not values, so duplicates change nothing. Expected [[-1],[-1,-1]].

Follow-ups interviewers ask

How would you return the levels from the bottom up, as in Binary Tree Level Order Traversal II?
Run the same BFS, then reverse the list of levels at the end. That is O(n) extra and keeps each level's left to right order. You can also insert each new level at the front of a deque, which avoids the final reversal.
How do you get a zigzag order, where odd levels go right to left?
Keep the BFS as is and track the level index. When the index is odd, reverse that level's list before appending it, or fill a preallocated array from the back. The queue order must stay left to right, because the children of the next level depend on it.
Can you do it in O(1) extra space beyond the output?
Not with the standard queue, since a complete tree's widest level is about n / 2 nodes. Recursive DFS needs O(h) stack and is O(log n) on a balanced tree, but O(n) on a chain. If nodes had parent pointers you could walk level by level with no queue, but the input tree does not give them. Constant space in general would require modifying the tree, such as a Morris-style threaded traversal, which is far more complex than it is worth here.

Binary Tree Level Order Traversal FAQ

What is the time complexity of Binary Tree Level Order Traversal?

The BFS and DFS solutions are both O(n), where n is the number of nodes, because every node is handled once with constant work. The brute force that traverses once per level is O(n * h), which is O(n^2) on a chain.

Why use a queue for Binary Tree Level Order Traversal?

A queue is first in, first out, so children wait behind every node already queued. That keeps nodes in depth order. Reading the queue size at the start of each round then tells you where the current level ends.

What is the space complexity of the BFS solution?

It is O(n). The queue holds at most about one level at a time, and a complete tree's bottom level has roughly n / 2 nodes. The output also stores all n values.

Can Binary Tree Level Order Traversal be solved with recursion?

Yes. Pass the depth into a DFS, create a new list when the depth first appears, and append the node's value to that depth's list. Visit left before right and the order inside each level is correct. In Python, raise the recursion limit, because a 2000-node chain exceeds the default of 1000.

Can Binary Tree Level Order Traversal be solved in O(1) extra space?

Not in a useful way. Level order needs to remember the pending nodes of a level, and that can be about n / 2 nodes. The recursive version trades that for stack depth, which is also O(n) on a chain.

Why store the queue size before the inner loop in LeetCode 102?

Pushing children changes the queue length during the loop. If the loop condition reads the live size, it keeps going into the next level and merges the two. A fixed k stops the round after exactly one level.

Asked at

See which companies ask this — Pro

Practise it