Maximum width of binary tree solution explained

The maximum width of a binary tree is the largest, over all levels, of the distance between the leftmost and rightmost nodes of a level, counting the empty slots in between as if the tree were complete. Give each node a position (children of position p sit at 2p and 2p + 1), run a level-by-level BFS, and take the last position minus the first plus one on each level. Renumbering each level from zero keeps every position below about twice the answer, for O(n) time and O(w) space.

By Published 7 min read

The problem in plain words

Imagine laying the tree out as if it were complete: every level fully filled, with a slot for every possible node. On each level, look at the leftmost and rightmost slots that hold real nodes. The level's width is the number of slots from one to the other, inclusive, including empty ones in between. Return the largest width of any level. An empty tree has width 0.

          4                 level 0: [4]            width 1
        /   \
       9     2              level 1: [9, 2]         width 2
        \     \
         6     5            level 2: [_, 6, _, 5]   width 3 (slots 1..3)
              /
             3              level 3: only slot 6    width 1
Our example: the answer is 3, from the third level

On level 2, node 6 is the right child of 9 and node 5 is the right child of 2. In a complete layout they sit in slots 1 and 3, so the width counts slots 1, 2 and 3. Note that the deepest level is not the widest here: it holds a single node.

Why it is a good interview question

It looks like a level order traversal, and it is, but counting nodes per level gives the wrong answer because gaps count. The question tests whether you can find a representation, positions, that makes gaps cheap to measure, and whether you notice the overflow hiding in it. Interviewers often let a candidate write the position solution and then ask what happens on a tree that is a few thousand levels deep.

Brute force: queue the empty slots too

Run BFS but enqueue a placeholder whenever a child is missing, and give placeholders two placeholder children. On each level, trim placeholders from both ends and measure what remains. It mirrors the definition exactly. The problem is size: the slots between the outermost nodes double every level, so a tree with just two long branches running down opposite edges makes the queue hold about 2 to the power of the depth entries while having only a few hundred real nodes. That is fine for a sketch on the whiteboard and hopeless for a real input.

Positions instead of placeholders

Number the slots of each level from the left, starting at 0. A node in slot p has its children in slots 2p and 2p + 1 of the next level. That is the same numbering a binary heap uses in an array. Now only real nodes are queued, each carrying its slot number, and a level's width is simply its last slot minus its first slot plus one, because BFS keeps each level in left-to-right order.

One catch remains. Slot numbers double at every level, so after 64 levels they no longer fit in 64 bits, and after 53 they lose precision in a JavaScript number. The fix is to renumber: before computing a level's children, subtract the level's first slot from every slot on it. Widths are differences, so they do not change, and every slot stays below twice the level's width. As long as the answer fits in an ordinary integer, so does every position; if the width itself can be astronomically large, only big integers will do.

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def max_width(root):
    if root is None:
        return 0
    best = 0
    level = [(root, 0)]                     # (node, position within its level)
    while level:
        first = level[0][1]
        best = max(best, level[-1][1] - first + 1)
        below = []
        for node, pos in level:
            pos -= first                    # renumber from 0 so positions stay small
            if node.left:
                below.append((node.left, 2 * pos))
            if node.right:
                below.append((node.right, 2 * pos + 1))
        level = below
    return best
Python, BFS with renumbered positions. O(n) time, O(w) space.
function maxWidth(root) {
  if (!root) return 0;
  let best = 0;
  let level = [[root, 0]];
  while (level.length > 0) {
    const first = level[0][1];
    best = Math.max(best, level[level.length - 1][1] - first + 1);
    const below = [];
    for (const [node, p] of level) {
      const pos = p - first; // positions now stay below twice the level width
      if (node.left) below.push([node.left, 2 * pos]);
      if (node.right) below.push([node.right, 2 * pos + 1]);
    }
    level = below;
  }
  return best;
}
JavaScript, same idea. Without the renumbering, a right-leaning chain 60 levels deep that ends in two leaves already reports the wrong width.

Python integers never overflow, so the renumbering there is about keeping numbers small and fast rather than correct. Keep it anyway; it carries over to every other language.

A depth-first alternative

You can also walk the tree depth-first, passing (depth, position), and remember the first position seen at each depth. Visiting left before right, the first node reached at a depth is the leftmost one, so each later node at that depth gives a candidate width: its position minus the stored first position plus one. This uses O(h) memory instead of O(w), but it cannot renumber level by level as simply, so it needs big integers or modular care on deep trees. Mention it as an option; the BFS is the safer answer.

Complexity

n nodes, height h, widest level w (counting real nodes)
ApproachTimeExtra space
BFS with placeholder slotsO(2^h) in the worst caseO(2^h)
BFS with renumbered positionsO(n)O(w)
DFS with first position per depthO(n), plus big-integer cost on deep treesO(h)
n nodes, height h, widest level w (counting real nodes). Scroll sideways on a small screen.

Edge cases to test

  • Empty tree: 0. Single node: 1.
  • A one-sided chain: every level has width 1, and positions explode without renumbering.
  • A tree whose two outermost branches run deep on opposite sides: the bottom width is huge even though the tree has few nodes, and the answer itself may need big integers.
  • A widest level that is not the deepest, as in the example.
  • Levels with one node, where last minus first plus one must give 1.

Common mistakes

  • Counting nodes per level and ignoring gaps.
  • Using p * 2 positions without renumbering in a language with fixed-size integers.
  • Renumbering children with the next level's first position instead of the current level's, which shifts the wrong values.
  • Measuring width from position 0 instead of from the level's first real node.
  • Queueing null children and then reading their positions.

How to explain it out loud

Fictional example

A concise explanation
Candidate
Width counts empty slots, so I will give every node its slot number as if the tree were complete: children of slot p are 2p and 2p plus 1.
Candidate
With BFS, each level comes out left to right, so its width is last slot minus first slot plus one.
Candidate
Slot numbers double every level, so I subtract the level's first slot before computing children. Widths are differences, so nothing changes, and numbers stay small.
Candidate
Each node is processed once: O(n) time, and the queue holds one level at a time.

The level-by-level loop here is the one from Binary Tree Level Order Traversal. Rebuilding a tree from position-free information is the opposite exercise, in Construct Binary Tree from Inorder and Postorder, and a tree question that needs bottom-up decisions instead of levels is Binary Tree Cameras. See the coding problems hub for more.

Practicing with Natively

Drawing the slot numbers is the fastest way to see this problem, and also the easiest place to mislabel a child. During practice, Natively can read your tree from a screenshot on Mac or Windows, label each node's slot, and ask the overflow follow-up an interviewer might raise. A transcript of the mock lets you check whether you explained the renumbering before writing it.

Questions people ask

How do you find the maximum width of a binary tree?

Give each node a position, with children of position p at 2p and 2p + 1. Run BFS level by level and take the last position minus the first plus one on each level; the largest value is the answer.

Why do positions overflow in maximum width of binary tree?

Positions double at every level, so a deep tree exceeds fixed-size integers. Subtracting each level's first position before computing children keeps them below about twice the level's width.

Does the width count null nodes?

Only the empty slots between a level's leftmost and rightmost real nodes, as if the tree were complete. Empty slots outside them do not count.

What is the complexity of the maximum width solution?

O(n) time, since each node is queued once, and O(w) extra space for the widest level.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP