Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Trees/Tree BFS (Level Order)

Learn the pattern · ~14 min

Tree BFS (Level Order)

also called level order traversal

Use a queue, and at the start of each round count what's in it: exactly those nodes are one level, and the children they push form the next.

Signalsanything 'per level' (averages, right view, zigzag)minimum depth / nearest leafwidth of a level
Cheat sheet and practice

Reach for it when you read

  • +The answer is per level: the values of each row, a sum or average per depth, the largest value in each row.
  • +"The first / last node on each level": a right or left side view.
  • +The nearest something from the root: minimum depth, the first leaf, the shallowest node that matches.
  • +Positions along a row matter: the width of a level, or nodes grouped by column.
  • +Something spreads one step per minute from a node (infection, distance k): BFS rounds are the minutes.

Not this one when

  • ×The answer depends on a root-to-leaf path or on what both subtrees report (path sums, diameter, LCA): tree DFS.
  • ×A BST question about order (k-th smallest, validate, range): an in-order walk, not levels.
  • ×Shortest path in a weighted graph: a queue of rounds is wrong there; use Dijkstra.

Learn Tree BFS (Level Order)

First, what do "BFS" and "level" mean?

BFS stands for breadth-first search: finish everything at one distance from the start before going one step further. In a tree, that distance from the root is the level (or depth): the root is on level 0, its children on level 1, and so on. Our tree for the whole page:

Text
        1
       / \
      2   3
     / \   \
    4   5   6
       /
      7

Level 0 is 1. Level 1 is 2 3. Level 2 is 4 5 6. Level 3 is 7.

Tree BFS visits the nodes in that order, level by level, left to right. It uses a queue: you join at the back and leave from the front.

How does a queue give us levels?

The rule is one line:

Pop the node at the front, use it, and push its children to the back.

Start with only the root in the queue.

step pop what happens queue after (front → back)
1 1 1 has two children: push 2, then 3 2, 3
2 2 push its children 4 and 5 behind 3 3, 4, 5
3 3 it has only a right child: push 6 4, 5, 6
4 4 a leaf, nothing to push 5, 6
5 5 push its left child 7 6, 7
6 6 a leaf 7
7 7 a leaf, and the queue is empty: done empty

The pops come out 1 2 3 4 5 6 7, level by level: children join behind everyone already waiting, so the level below never overtakes. And look at the queue after step 3: 4, 5, 6, all of level 2 and nothing else.

The code for it

C++
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
    int size = q.size();                // freeze it: exactly this many nodes are one level
    for (int i = 0; i < size; i++) {
        TreeNode* node = q.front(); q.pop();
        cout << node->val << ' ';       // use the node
        if (node->left) q.push(node->left);
        if (node->right) q.push(node->right);
    }
    cout << '\n';                       // one level is done
}

It prints 1, 2 3, 4 5 6, 7, one level per line. You don't need to memorise this. It's the table above cut into rounds: at the start of a round the queue holds one whole level, so count it and pop exactly that many.

Why read size before the loop, not i < q.size()? The queue grows during the round. Round 1 starts with 2, 3; after popping 2 it is 3, 4, 5, so q.size() would let the round pop 4 too, leaking level 2 into level 1.

round size frozen pops pushes queue after
0 1 1 2, 3 2, 3
1 2 2, 3 4, 5, 6 4, 5, 6
2 3 4, 5, 6 7 7
3 1 7 none empty

Fine, but how does this help us?

Here's a classic problem: maximum width of a binary tree. A level's width is the distance from its leftmost to its rightmost node, counting the empty gaps between them as if the tree were complete. Return the largest width over all levels.

On our tree, by hand:

level nodes how you count it width
0 1 one node 1
1 2, 3 side by side 2
2 4, 5, _, 6 3 has no left child, so there's a hole between 5 and 6 4
3 7 one node 1

The answer is 4, from level 2.

The brute force

Pad the tree with nulls so each level has all its slots. A level's width is then last real slot − first real slot + 1.

C++
long long widthBrute(TreeNode* root) {
    vector<TreeNode*> level = {root};       // every slot of this level, nulls included
    long long best = 0;
    while (true) {
        int first = -1, last = -1;
        for (int i = 0; i < (int)level.size(); i++)
            if (level[i]) { if (first < 0) first = i; last = i; }
        if (first < 0) break;               // a level with no real node: done
        best = max(best, (long long)(last - first + 1));
        vector<TreeNode*> next;             // two slots under every slot, even empty ones
        for (TreeNode* n : level) {
            next.push_back(n ? n->left : nullptr);
            next.push_back(n ? n->right : nullptr);
        }
        level = next;
    }
    return best;
}

It gets 4 too. But level d has 2^d slots, real or not. Timed with -O2, a chain of just 28 nodes going right already takes 2 seconds; each extra node doubles that, and the problem allows 3,000 nodes. Time limit exceeded.

The one thought that fixes it

Stop at level 2, node 6. The brute force builds four slots there: 4, 5, an empty one, 6. But the width only needs 6's slot, 3, and 4's slot, 0: 3 − 0 + 1 = 4. The empty slot itself was never needed.

Can a node know its slot without the empty ones existing? Number each level's slots from 0. Every slot owns exactly two slots below it, so a node in slot i has its children in slots 2i and 2i + 1.

  • 3 sits in slot 1 of level 1, so its right child 6 gets slot 2·1 + 1 = 3.
  • 5 sits in slot 1 of level 2, so its left child 7 gets slot 2·1 = 2.

So carry (node, slot) pairs. At the start of a round the queue holds the whole level left to right, so the width is back slot − front slot + 1.

One trap: slots double every level, and 64 levels down a right chain the slot is 2⁶⁴ − 1, past 64 bits. So subtract the level's first slot before computing children. Only differences matter, so no width changes, and slots stay below twice the width.

C++
long long widthOfBinaryTree(TreeNode* root) {
    queue<pair<TreeNode*, long long>> q;    // (node, position on its level)
    q.push({root, 0});
    long long best = 0;
    while (!q.empty()) {
        long long first = q.front().second, last = q.back().second;
        best = max(best, last - first + 1);
        for (int k = q.size(); k > 0; k--) {
            auto [node, i] = q.front(); q.pop();
            i -= first;                     // re-base: the level's first node is at 0
            if (node->left)  q.push({node->left,  2 * i});
            if (node->right) q.push({node->right, 2 * i + 1});
        }
    }
    return best;
}

Dry run

Same tree. The queue at the start of each round, written as node@slot:

level queue at the start front, back width best
0 1@0 0, 0 1 1
1 2@0, 3@1 0, 1 2 2
2 4@0, 5@1, 6@3 0, 3 4 4
3 7@2 2, 2 1 4

The answer is 4, the same answer as the brute force. On a chain of 70 right children it returns 1, and every slot stays 0 or 1.

Why it's O(n)

Count what happens to each node: it is pushed once and popped once, with O(1) work in between. No empty slot is ever created: O(n) time.

The queue holds at most about two levels: O(w) space for the widest level w.

From 2^depth slots to n nodes, by numbering the real nodes instead of building the empty ones.

Right side view? Keep the last one

Standing to the right of the tree, you see the last node popped in each round.

C++
if (i == size - 1) out.push_back(node->val);   // the last node popped this round

On our tree: 1, 3, 6, 7. Keep i == 0 instead for the left side view: 1, 2, 4, 7.

Minimum depth? Stop at the first leaf

Minimum depth counts the nodes on the shortest root-to-leaf path. BFS meets leaves in order of depth, so stop at the first one:

C++
if (!node->left && !node->right) return depth;   // the first leaf popped is the nearest

Count depth from 1 at the root's round. The first leaf popped is 4, on level 2, so the minimum depth is 3. A DFS would have to reach every leaf to be sure; BFS stops at the first.

Remember this

  • Freeze size before the round starts, or levels leak into each other.
  • Positions along a level: the children of slot i are 2i and 2i + 1; re-base by the level's first slot every round, or the numbers overflow.
  • Nearest from the root (the first leaf, the shallowest match): BFS, and stop at the first hit.
  • Whenever a tree question asks something per level or row, or how far from the root, it's tree BFS: one round per level. A path from the root is DFS.

Practise it on Binary Tree Level Order Traversal, then Average of Levels in Binary Tree (one number per round; sum in 64 bits), Binary Tree Right Side View, Minimum Depth of Binary Tree (stop early), Binary Tree Zigzag Level Order Traversal (reverse odd rounds) and Maximum Width of Binary Tree (slots).

Below, watch Binary Tree Level Order Traversal run line by line.

Watch it work, line by line

Binary Tree Level Order Traversal ↗, root = [3, 9, 20, null, null, 15, 7] → [[3], [9, 20], [15, 7]]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Is the question about rows of the tree (per level, first or last on each level, the nearest leaf), rather than about paths from the root?

Reach for it when

  • +anything 'per level' (averages, right view, zigzag)
  • +minimum depth / nearest leaf
  • +width of a level
  • +n up to 1e4-1e5

It fails when

  • ×Root-to-leaf paths or a recursive subtree property (height, diameter)use Tree DFS
  • ×Memory matters and the tree is bushy (BFS holds up to n/2 nodes)use DFS, O(height) space
  • ×Weighted shortest pathuse Dijkstra, not plain BFS

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why read q.size() before the inner loop, not inside it?Reveal

    Children pushed during the loop belong to the next level. Reading the size first freezes exactly the current level.

  • 2Minimum depth: when do you stop?Reveal

    At the first node with no children (a leaf), not the first missing child. A node with one child isn't a leaf.

  • 3How much memory can BFS take on a full binary tree, and how does DFS compare?Reveal

    Up to about n/2 nodes in the queue (the last level). DFS needs only O(height).

Practice ladder

every problem →
  1. 1Binary Tree Level Order Traversalthe hookMedium
  2. 2Average of Levels in Binary Treea number per levelEasy
  3. 3Binary Tree Right Side Viewone node per levelMedium
  4. 4Minimum Depth of Binary Treestop at the first leafEasy
  5. 5Binary Tree Zigzag Level Order TraversalzigzagMedium
  6. 6Populating Next Right Pointers in Each Nodelink each levelMedium
  7. 7Maximum Width of Binary Treepositions on a levelMedium
  8. 8Amount of Time for Binary Tree to Be Infectedspread from any nodeMedium

Finished Tree BFS (Level Order)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Tree BFS (Level Order)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial