Browse curriculum

Maximum Width of Binary Tree (LeetCode 662)

Maximum Width of Binary Tree (LeetCode 662): find the widest level of the tree (including nulls between end nodes).

Medium
15 min
Solve on LeetCode

Examples

Input:root = [1,3,2,5,3,null,9]
Output:4
Explain:

The last level spans slots 0 to 3, including one empty slot.

Input:root = [1,3,2,5,null,null,9,6,null,7]
Output:7
Explain:

The last level spans slots 0 to 6: 6 and 7 with five empty slots between.

Input:root = [1,3,2,5]
Output:2
Explain:

The second level, 3 and 2, is widest.

Problem Understanding

Find the maximum width of the binary tree under root, taken over all of its levels.

  • Width: The number of nodes between the leftmost and rightmost non-null nodes in a level, including the null nodes between them.
  • Imagine filling the tree into a complete binary tree structure. We count the distance from Start to End index.

Algorithm Strategy

Give every node the index it would have in a complete binary tree, and the gaps take care of themselves.

  1. Indices: the root is 0. A node at index i has its left child at 2i and its right child at 2i + 1. Two nodes on a level with indices 0 and 3 have two empty slots between them.
  2. BFS with pairs: the queue holds (node, index).
  3. Width at the start of a level: the front of the queue holds the smallest index, first, and the back holds the largest, last. The width is last - first + 1.
  4. Keep indices small: as each node is dequeued, subtract first from its index before computing its children's. Every level then starts near 0, however deep the tree is.

Interactive Visualization

i = INDEX ENQUEUED WITH · CHILDREN OF i ARE 2i AND 2i + 1

ENQUEUE (root, 0)

first

:

last

:

best

0

level slots

No level being measured

queue (front first)

(1, 0)

 

best = 0. Put (1, index 0) in the queue

Next

A new level of 1 node: first = 0 at the front, last = 0 at the back

Free preview: the first 8 of 25 steps

Tree

Every node shows the index it was enqueued with. When a level starts, its slots are laid out beside the tree from first to last (nodes and ∅ gaps alike) and the width is the number of slots. Try Example 2, where the last level has five empty slots between its two nodes.

Dry Run

Tree: [1, 3, 2, 5, 3, null, 9] (LeetCode example 1).

Level Queue at start (value, index) first last width best
0 (1, 0) 0 0 1 1
1 (3, 0), (2, 1) 0 1 2 2
2 (5, 0), (3, 1), (9, 3) 0 3 4 4

Slot 2 on the last level is empty (it is where 2's left child would be) but it lies between the first and last nodes, so it counts. The method returns 4.

Edge Cases & Common Mistakes

Edge Cases:

  • Single node: width 1.
  • Index size: subtracting first keeps indices below twice the widest level seen so far, and LeetCode guarantees the answer fits in a 32-bit integer, but twice that does not, so Java, C++ and C keep indices in 64-bit integers. Python integers and JavaScript numbers hold them exactly.

Common Mistakes:

  • Counting only the non-null nodes on a level. The empty slots between the first and last node are part of the width.
  • Measuring the width after the level has been dequeued, when the queue already holds the next level.

Solution Code

BFS with Indexing Normalization.

Maximum Width of Binary Tree Code
1var widthOfBinaryTree = function(root) {
2 let best = 0;
3 const queue = [[root, 0]];
4 let head = 0;
5 while (head < queue.length) {
6 const size = queue.length - head;
7 const first = queue[head][1];
8 const last = queue[queue.length - 1][1];
9 best = Math.max(best, last - first + 1);
10 for (let i = 0; i < size; i++) {
11 let [node, index] = queue[head++];
12 index -= first;
13 if (node.left) {
14 queue.push([node.left, 2 * index]);
15 }
16 if (node.right) {
17 queue.push([node.right, 2 * index + 1]);
18 }
19 }
20 }
21 return best;
22};

Maximum Width of Binary Tree in Python, Java, C++, TypeScript and C

Maximum Width of Binary Tree in Python
from collections import deque


class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        best = 0
        queue = deque([(root, 0)])
        while queue:
            size = len(queue)
            first = queue[0][1]
            last = queue[-1][1]
            best = max(best, last - first + 1)
            for _ in range(size):
                node, index = queue.popleft()
                index -= first
                if node.left:
                    queue.append((node.left, 2 * index))
                if node.right:
                    queue.append((node.right, 2 * index + 1))
        return best
Maximum Width of Binary Tree in Java
class Solution {
    private static class Entry {
        final TreeNode node;
        final long index;

        Entry(TreeNode node, long index) {
            this.node = node;
            this.index = index;
        }
    }

    public int widthOfBinaryTree(TreeNode root) {
        long best = 0;
        Deque<Entry> queue = new ArrayDeque<>();
        queue.offer(new Entry(root, 0));
        while (!queue.isEmpty()) {
            int size = queue.size();
            long first = queue.peekFirst().index;
            long last = queue.peekLast().index;
            best = Math.max(best, last - first + 1);
            for (int i = 0; i < size; i++) {
                Entry entry = queue.poll();
                long index = entry.index - first;
                if (entry.node.left != null) {
                    queue.offer(new Entry(entry.node.left, 2 * index));
                }
                if (entry.node.right != null) {
                    queue.offer(new Entry(entry.node.right, 2 * index + 1));
                }
            }
        }
        return (int) best;
    }
}
Maximum Width of Binary Tree in C++
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        unsigned long long best = 0;
        deque<pair<TreeNode*, unsigned long long>> q;
        q.push_back({root, 0});
        while (!q.empty()) {
            int size = q.size();
            unsigned long long first = q.front().second;
            unsigned long long last = q.back().second;
            best = max(best, last - first + 1);
            for (int i = 0; i < size; i++) {
                auto [node, index] = q.front();
                q.pop_front();
                index -= first;
                if (node->left) {
                    q.push_back({node->left, 2 * index});
                }
                if (node->right) {
                    q.push_back({node->right, 2 * index + 1});
                }
            }
        }
        return (int)best;
    }
};
Maximum Width of Binary Tree in TypeScript
function widthOfBinaryTree(root: TreeNode | null): number {
    let best = 0;
    const queue: [TreeNode, number][] = [[root!, 0]];
    let head = 0;
    while (head < queue.length) {
        const size = queue.length - head;
        const first = queue[head][1];
        const last = queue[queue.length - 1][1];
        best = Math.max(best, last - first + 1);
        for (let i = 0; i < size; i++) {
            let [node, index] = queue[head++];
            index -= first;
            if (node.left) {
                queue.push([node.left, 2 * index]);
            }
            if (node.right) {
                queue.push([node.right, 2 * index + 1]);
            }
        }
    }
    return best;
}
Maximum Width of Binary Tree in C
struct Entry {
    struct TreeNode* node;
    unsigned long long index;
};

int widthOfBinaryTree(struct TreeNode* root) {
    unsigned long long best = 0;
    struct Entry* queue = malloc(3000 * sizeof(struct Entry));
    int head = 0, tail = 0;
    queue[tail++] = (struct Entry){root, 0};
    while (head < tail) {
        int size = tail - head;
        unsigned long long first = queue[head].index;
        unsigned long long last = queue[tail - 1].index;
        if (last - first + 1 > best) {
            best = last - first + 1;
        }
        for (int i = 0; i < size; i++) {
            struct Entry entry = queue[head++];
            unsigned long long index = entry.index - first;
            if (entry.node->left) {
                queue[tail++] = (struct Entry){entry.node->left, 2 * index};
            }
            if (entry.node->right) {
                queue[tail++] = (struct Entry){entry.node->right, 2 * index + 1};
            }
        }
    }
    free(queue);
    return (int)best;
}

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

The approach, step by step

  1. Index the root

    Enqueue the root with index 0.

  2. Measure each level

    Before dequeuing a level, take first from the front and last from the back; the width is last − first + 1.

  3. Index the children

    Dequeue each node, subtract first from its index i, and enqueue its children at 2i and 2i + 1.

Frequently asked questions

Why do the null gaps count toward the width?

The problem defines width as the distance between the leftmost and rightmost nodes of a level as if the tree were complete, so empty slots between them count as positions.


Why subtract first from each index?

Indices double with every level, so a deep tree would produce huge numbers. Subtracting the level's first index as each node is dequeued keeps every level's indices close to 0 without changing any width.


Why use 64-bit indices in Java, C++ and C?

The answer fits in 32 bits, but a child's index can be about twice the width of its parent's level. 64-bit integers hold that intermediate value safely.

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