3 min readRishi

Binary Tree Level Order Traversal: The BFS Template

"Binary Tree Level Order Traversal" is a Medium-level staple in Amazon, Microsoft, Meta loops, and it is a textbook fit for the Tree BFS pattern — one of the nine patterns that cover the bulk of what FAANG coding interviews actually test. Part 1 of 11 in the Tree BFS arc.

The Problem

Given the root of a binary tree, return the level order traversal of its nodes' values — a list per level, left to right. This is the template question: the snapshot loop you write here is reused, nearly unchanged, by most of the BFS family.

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

Recognizing the Tree BFS Pattern

Breadth-first search explores a tree or graph level by level using a queue, and its defining superpower is the level snapshot: freeze the queue length, process exactly that many nodes, and you have processed one complete level. Anything phrased per-level — level lists, level averages, rightmost visible node, shortest path in unweighted structures — is BFS by construction.

Grouped-by-level output is the least ambiguous BFS cue that exists. The subtlety is the snapshot: len(queue) at the top of each round is exactly the size of the current level, because children enqueued during the round belong to the next one.

The Approach

Seed a deque with the root. Each outer iteration captures len(queue), pops exactly that many nodes — collecting values and enqueuing children — and appends the collected list. When the queue drains, every level has been emitted in order.

Use collections.deque, and pop from the left: list.pop(0) is O(n) per pop and converts the whole traversal to O(n²). Interviewers at Meta specifically look for this detail in Python candidates.

Python Solution

class TreeNode:
    def __init__(self, val: int = 0, left: "TreeNode | None" = None,
                 right: "TreeNode | None" = None):
        self.val = val
        self.left = left
        self.right = right


from collections import deque


def level_order(root: TreeNode | None) -> list[list[int]]:
    """Values grouped by level, left to right."""
    if not root:
        return []
    result: list[list[int]] = []
    queue: deque[TreeNode] = deque([root])
    while queue:
        level: list[int] = []
        for _ in range(len(queue)):        # snapshot: this level only
            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

Complexity

  • Time: O(n) — every node enters and leaves the queue exactly once
  • Space: O(w) — the queue holds at most one level — w is the tree's max width

Interview Tips and Follow-Ups

  • Say 'O(w) queue, up to n/2 on a complete tree' — width-aware space analysis separates practiced candidates from template reciters.
  • DFS with a depth parameter can also produce level lists — mention it, note BFS is canonical, and move on.
  • Every remaining question in this arc is this loop with one line changed — say that at the end and mean it.

If this clicked, continue the Tree BFS arc in the Technical Interview category. One hundred questions, nine patterns, all in Python.

Keep reading

Newsletter

New posts, straight to your inbox

One email per post. No spam, no tracking pixels, unsubscribe anytime.

Comments

  • No comments yet. Be the first.