Browse curriculum

Binary Tree Level Order Traversal (LeetCode 102)

Binary Tree Level Order Traversal (LeetCode 102): return a binary tree's values level by level with BFS: read the queue size to know how many nodes form the current level, then enqueue their children.

Problem Understanding

Binary Tree Level Order Traversal: given the root of a binary tree, return its node values level by level, left to right, as a list of lists.

Example: root = [3, 9, 20, null, null, 15, 7] returns [[3], [9, 20], [15, 7]].

The Intuition: The Queue Holds One Level at a Time

Breadth-first search already visits a tree level by level; the only work is knowing where each level ends.

  1. Start with the root in a queue.
  2. At the top of each pass, the queue contains exactly one level. Read size = len(queue).
  3. Dequeue size nodes, recording their values and enqueuing their children.
  4. Append the recorded list as one row; the queue now holds the next level.

The same loop with one extra step solves Zigzag Level Order (reverse every other row) and Binary Tree Right Side View (keep the last node of each row).

Binary Tree Level Order Traversal Visualization

#n = DEQUEUE ORDER · ROWS BESIDE = OUTPUT

ENQUEUE ROOT

Level

0

Levels done

0

queue (front first)

3

level list

Not collecting

result

[]

 

Put the root, 3, in the queue

Next

Level 0: the queue holds 1 node, exactly this level

Free preview: the first 7 of 22 steps

Tree

The tree numbers each node #n in the order it is dequeued. Beside it are the queue, the level being collected and the finished rows. Try Lopsided to see a level that holds a single node.

Binary Tree Level Order Traversal Dry Run

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

Pass Queue at start Size Row Queue after
1 [3] 1 [3] [9, 20]
2 [9, 20] 2 [9, 20] [15, 7]
3 [15, 7] 2 [15, 7] []

Answer: [[3], [9, 20], [15, 7]].

Binary Tree Level Order Traversal LeetCode Solution

BFS with the queue size read at the start of each level.

Binary Tree Level Order Traversal Code
1var levelOrder = function(root) {
2 const result = [];
3 if (!root) {
4 return result;
5 }
6 const queue = [root];
7 let head = 0;
8 while (head < queue.length) {
9 const size = queue.length - head;
10 const level = [];
11 for (let i = 0; i < size; i++) {
12 const node = queue[head++];
13 level.push(node.val);
14 if (node.left) {
15 queue.push(node.left);
16 }
17 if (node.right) {
18 queue.push(node.right);
19 }
20 }
21 result.push(level);
22 }
23 return result;
24};

Binary Tree Level Order Traversal in Python, Java, C++, TypeScript and C

Binary Tree Level Order Traversal in Python
from collections import deque


class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        result = []
        if not root:
            return result
        queue = deque([root])
        while queue:
            size = len(queue)
            level = []
            for _ in range(size):
                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
Binary Tree Level Order Traversal in Java
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            result.add(level);
        }
        return result;
    }
}
Binary Tree Level Order Traversal in C++
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if (!root) {
            return result;
        }
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int size = q.size();
            vector<int> level;
            for (int i = 0; i < size; i++) {
                TreeNode* node = q.front();
                q.pop();
                level.push_back(node->val);
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            result.push_back(level);
        }
        return result;
    }
};
Binary Tree Level Order Traversal in TypeScript
function levelOrder(root: TreeNode | null): number[][] {
    const result: number[][] = [];
    if (!root) {
        return result;
    }
    const queue: TreeNode[] = [root];
    let head = 0;
    while (head < queue.length) {
        const size = queue.length - head;
        const level: number[] = [];
        for (let i = 0; i < size; i++) {
            const node = queue[head++];
            level.push(node.val);
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        result.push(level);
    }
    return result;
}
Binary Tree Level Order Traversal in C
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
    int** result = malloc(2000 * sizeof(int*));
    *returnColumnSizes = malloc(2000 * sizeof(int));
    *returnSize = 0;
    if (!root) {
        return result;
    }
    struct TreeNode** queue = malloc(2000 * sizeof(struct TreeNode*));
    int head = 0, tail = 0;
    queue[tail++] = root;
    while (head < tail) {
        int size = tail - head;
        int* level = malloc(size * sizeof(int));
        for (int i = 0; i < size; i++) {
            struct TreeNode* node = queue[head++];
            level[i] = node->val;
            if (node->left) {
                queue[tail++] = node->left;
            }
            if (node->right) {
                queue[tail++] = node->right;
            }
        }
        (*returnColumnSizes)[*returnSize] = size;
        result[(*returnSize)++] = level;
    }
    free(queue);
    return result;
}

Edge Cases & Common Mistakes

  • Empty tree: return [], not [[]].
  • Using len(queue) inside the loop condition: the queue grows while you iterate; read the size once before the inner loop.
  • Enqueuing null children: skip them, or every level fills up with nulls.
  • Using a list as a queue in Python: list.pop(0) is O(n); use collections.deque.
  • Bottom-up variant (LeetCode 107): run the same loop and reverse the result at the end.

Summary

Put the root in a queue. Each pass, read the queue size, dequeue that many nodes into one row, and enqueue their children for the next pass. Append the rows until the queue is empty. O(n) time and O(w) space, where w is the widest level.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start the queue

    Return [] for an empty tree; otherwise put the root in a queue.

  2. Take one level per pass

    Read the queue size, then dequeue that many nodes, appending each value to a level list and enqueuing its non-null children.

  3. Collect the rows

    Append each level list to the result until the queue is empty.

Frequently asked questions

How does BFS separate a binary tree into levels?

At the start of each pass the queue holds exactly the nodes of one level. Read its size first, dequeue that many nodes into a list, and enqueue their children. Those children are the next level, so each pass produces one row of the answer.


Why read the queue size before the inner loop?

Children are added to the queue while the level is being processed. Reading the size first fixes how many nodes belong to the current level, so the new children wait for the next pass instead of being mixed into this row.


Can level order traversal be done with DFS?

Yes. Pass the depth into a recursive function and append each value to result[depth], creating the row the first time a depth is reached. It gives the same answer, but BFS matches the problem's shape more directly.

New to the technique behind this problem? Watch it run step by step:

Breadth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description