BackmediumArraysarraysmedium

Maximum Binary Tree Width Solution

Problem Statement

Given the root of a binary tree, determine the maximum width of the tree. The width of a specific level is defined as the number of nodes present at that depth, including any null positions that lie between the leftmost and rightmost non-null nodes. Your task is to compute the maximum value among all level widths in the tree.

The input is provided as a standard binary tree structure where each node contains an integer value and pointers to its left and right children. The output must be a single integer representing the widest level found in the tree. Note that the width calculation accounts for the structural span, meaning if a level has a node on the far left and a node on the far right with empty spaces in between, the width includes those empty slots.

For instance, if a level contains only one node, its width is 1. If a level has two nodes with no nodes between them, the width is 2. If there are gaps due to missing children in the hierarchy, the width expands to cover the full range from the first to the last node at that depth.

Example 1
Input
root = [1, 3, 2, 5, null, 9, 6]
Output
4

Explanation: Level 0: Node 1. Width = 1. Level 1: Nodes 3, 2. Width = 2. Level 2: Node 5 (left of 3), null (right of 3), Node 9 (left of 2), Node 6 (right of 2). The nodes are at positions 0, 1, 2, 3 relative to the level start. The span from the first node (5) to the last node (6) covers 4 positions. Width = 4. Maximum width is 4.

Example 2
Input
root = [1, 3, 2, 5, 3, 9, 6, 7, null, null, 4]
Output
8

Explanation: Level 0: Node 1. Width = 1. Level 1: Nodes 3, 2. Width = 2. Level 2: Nodes 5, 3, 9, 6. Width = 4. Level 3: Node 7 (left of 5), null (right of 5), null (left of 3), null (right of 3), null (left of 9), Node 4 (right of 9), null (left of 6), null (right of 6). The first node is 7 and the last is 4. The total span including nulls is 8. Width = 8. Maximum width is 8.

Example 3
Input
root = [1, null, 2, null, 3, null, 4]
Output
1

Explanation: Level 0: Node 1. Width = 1. Level 1: null, Node 2. The only non-null node is 2. Width = 1. Level 2: null, null, null, Node 3. The only non-null node is 3. Width = 1. Level 3: null, null, null, null, null, null, null, Node 4. The only non-null node is 4. Width = 1. Maximum width is 1.

Example 4
Input
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Output
8

Explanation: This is a complete binary tree of height 3. Level 0: 1 node. Width = 1. Level 1: 2 nodes. Width = 2. Level 2: 4 nodes. Width = 4. Level 3: 8 nodes. Width = 8. Maximum width is 8.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^4 <= Node.val <= 10^4
  • The tree is not necessarily balanced.
  • The depth of the tree is at most 10^4.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Maximum Binary Tree Width — Problem Statement & Solution Guide

ArraysMediumMixed
TimeO(N)
|
SpaceO(W)

Problem Description

Given the root of a binary tree, determine the maximum width of the tree. The width of a specific level is defined as the number of nodes present at that depth, including any null positions that lie between the leftmost and rightmost non-null nodes. Your task is to compute the maximum value among all level widths in the tree.

The input is provided as a standard binary tree structure where each node contains an integer value and pointers to its left and right children. The output must be a single integer representing the widest level found in the tree. Note that the width calculation accounts for the structural span, meaning if a level has a node on the far left and a node on the far right with empty spaces in between, the width includes those empty slots.

For instance, if a level contains only one node, its width is 1. If a level has two nodes with no nodes between them, the width is 2. If there are gaps due to missing children in the hierarchy, the width expands to cover the full range from the first to the last node at that depth.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Maximum Binary Tree Width"

medium

WHY DOES IT MATTER?

The pattern of assigning virtual positions to nodes during BFS is a cornerstone for problems that require accounting for missing elements, such as width calculations, serialization, and layout rendering. It transforms a structural property into a numeric one that can be processed in linear time.

OPTIMIZATION CHALLENGE

The key insight is index normalization per level, which prevents the indices from exploding as depth grows while still preserving relative distances needed for width computation.

REAL-WORLD CONNECTION

Think of a distributed hash table where each node occupies a slot in a logical ring; even if some slots are empty, the distance between two active nodes matters for load balancing. Similarly, the tree width measures the span of active nodes across a logical complete‑tree ring.

During the interview, start by describing the complete‑tree indexing, then immediately mention the normalization trick to keep numbers small—this shows you’re aware of both correctness and practical overflow concerns.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(W)

Core Theory — Why This Approach?

The maximum width of a binary tree is defined by the distance between the leftmost and rightmost non‑null nodes at each depth, counting the null slots that would exist between them. A naive level‑order traversal that simply counts the number of nodes per level fails because it ignores the gaps created by missing children, which can dramatically inflate the true width, especially in sparse trees. To capture these gaps, we assign a virtual index to each node as if the tree were a complete binary tree: the root gets index 0, its left child 2*i+1 and right child 2*i+2. The width of a level then becomes (lastIndex - firstIndex + 1). This indexing scheme enables a single BFS pass while preserving the exact positional information needed for the width calculation.

The optimal paradigm combines breadth‑first search with index normalization to avoid integer overflow. By subtracting the minimum index of the current level from all indices in that level, we keep values bounded within O(N) even for deep trees. This technique yields O(N) time, where N is the number of nodes, and O(W) auxiliary space, where W is the maximum number of nodes stored in the queue at any level (the tree's maximum width). The approach scales to large inputs where recursive depth‑first methods would risk stack overflow or where a plain BFS without indexing would misreport widths.

Interview Questions on This Problem

Q1How would you compute the maximum width of a binary tree without using extra space proportional to the number of nodes?

You can perform a depth‑first traversal while passing the depth and a running leftmost index for each depth. By tracking the first index seen at each depth, you can compute width as (currentIndex - leftmostIndex + 1) on the fly, achieving O(N) time and O(H) space, where H is the tree height.

Q2Why does using 64‑bit integers for node indices matter in this problem, and how can you mitigate overflow risks?

In a skewed tree, indices can grow exponentially (2^depth). Using 64‑bit integers prevents overflow for typical constraints, but a safer technique is to normalize indices each level by subtracting the minimum index of that level, keeping values bounded by the number of nodes at that level.

Q3Explain how the maximum width problem relates to the concept of a 'complete binary tree' representation.

By treating the given tree as if it were embedded in a complete binary tree, each node receives a deterministic position index. This virtual layout lets us measure the span of a level—including null slots—by simply subtracting the leftmost and rightmost indices, mirroring how nodes are arranged in a complete binary tree.

Examples

Example 1

Input

root = [1, 3, 2, 5, null, 9, 6]

Output

4

Explanation: Level 0: Node 1. Width = 1. Level 1: Nodes 3, 2. Width = 2. Level 2: Node 5 (left of 3), null (right of 3), Node 9 (left of 2), Node 6 (right of 2). The nodes are at positions 0, 1, 2, 3 relative to the level start. The span from the first node (5) to the last node (6) covers 4 positions. Width = 4. Maximum width is 4.

Example 2

Input

root = [1, 3, 2, 5, 3, 9, 6, 7, null, null, 4]

Output

8

Explanation: Level 0: Node 1. Width = 1. Level 1: Nodes 3, 2. Width = 2. Level 2: Nodes 5, 3, 9, 6. Width = 4. Level 3: Node 7 (left of 5), null (right of 5), null (left of 3), null (right of 3), null (left of 9), Node 4 (right of 9), null (left of 6), null (right of 6). The first node is 7 and the last is 4. The total span including nulls is 8. Width = 8. Maximum width is 8.

Example 3

Input

root = [1, null, 2, null, 3, null, 4]

Output

1

Explanation: Level 0: Node 1. Width = 1. Level 1: null, Node 2. The only non-null node is 2. Width = 1. Level 2: null, null, null, Node 3. The only non-null node is 3. Width = 1. Level 3: null, null, null, null, null, null, null, Node 4. The only non-null node is 4. Width = 1. Maximum width is 1.

Example 4

Input

root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Output

8

Explanation: This is a complete binary tree of height 3. Level 0: 1 node. Width = 1. Level 1: 2 nodes. Width = 2. Level 2: 4 nodes. Width = 4. Level 3: 8 nodes. Width = 8. Maximum width is 8.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^4 <= Node.val <= 10^4
  • The tree is not necessarily balanced.
  • The depth of the tree is at most 10^4.

Optimal Approach & Strategy

Perform BFS while assigning complete‑tree indices, normalize indices each level, and compute width as (lastIndex - firstIndex + 1).

Brute Force Approach

Traverse each level and simply count the existing nodes, ignoring null positions; this underestimates width for sparse trees.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function widthOfBinaryTree(root) { let max = 0; const queue = [[root, 0]]; while (queue.length) { const levelSize = queue.length; let min = Infinity, maxAtLevel = -Infinity; for (let i = 0; i < levelSize; i++) { const [node, index] = queue.shift(); min = Math.min(min, index); maxAtLevel = Math.max(maxAtLevel, index); if (node.left) queue.push([node.left, 2 * index + 1]); if (node.right) queue.push([node.right, 2 * index + 2]); } max = Math.max(max, maxAtLevel - min + 1); } return max; }

Asked in Top Tech Interviews

arraysmediumgeneric

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.