medium Maximum Width of Binary Tree
Problem Statement
Given the root of a binary tree, find the maximum width of the tree.
The maximum width is the widest level in the tree.
The width of a level is the number of nodes between the leftmost and rightmost non-null nodes, where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
You can assume that the result will fit within a 32-bit signed integer.
Examples
Example 1
- Input: root = [1, 2, 3, 4, null, null, 5]
- Output:
4 - Justification: The maximum width is at the last level between nodes 4 and 5. It counts four positions:
[4, null, null, 5].
Example 2
- Input: root = [1, 2, 3, 4, null, 5, 6, null, 7]
- Output:
4 - Justification: The maximum width is between nodes 4 and 6 at level 3, counting four positions:
[4, null, 5, 6].
Example 3
- Input: root = [1, 2, null, 3, 4, null, null, 5]
- Output:
2 - Justification: The maximum width is at the third level, between nodes 3 and 4. It counts two positions:
[3, 4].
Constraints:
- The number of nodes in the tree is in the range [1, 3000].
- -100 <= Node.val <= 100
Try it yourself
Try solving this question here:
✅ Solution Maximum Width of Binary Tree
Problem Statement
Given the root of a binary tree, find the maximum width of the tree.
The maximum width is the widest level in the tree.
The width of a level is the number of nodes between the leftmost and rightmost non-null nodes, where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
You can assume that the result will fit within a 32-bit signed integer.
Examples
Example 1
- Input: root = [1, 2, 3, 4, null, null, 5]
- Output:
4 - Justification: The maximum width is at the last level between nodes 4 and 5. It counts four positions:
[4, null, null, 5].
Example 2
- Input: root = [1, 2, 3, 4, null, 5, 6, null, 7]
- Output:
4 - Justification: The maximum width is between nodes 4 and 6 at level 3, counting four positions:
[4, null, 5, 6].
Example 3
- Input: root = [1, 2, null, 3, 4, null, null, 5]
- Output:
2 - Justification: The maximum width is at the third level, between nodes 3 and 4. It counts two positions:
[3, 4].
Constraints:
- The number of nodes in the tree is in the range [1, 3000].
- -100 <= Node.val <= 100
Solution
To solve this problem, we will use a level order traversal approach, where we traverse the tree level by level from left to right. During traversal, we keep track of each node's position in a hypothetical "complete binary tree" to account for all gaps (nulls) between nodes at each level. We use a queue to store nodes along with their positions, which allows us to calculate the width of each level easily. At each level, we compare the positions of the leftmost and rightmost nodes to determine the width. The maximum width found across all levels is our answer.
This approach is effective because it leverages a breadth-first search (BFS) technique to explore each level fully before moving to the next, ensuring that we capture the correct width of every level. It is efficient in both time and space, given that it only requires storing nodes at one level at a time, making it well-suited for handling binary trees of reasonable size.
Step-by-Step Algorithm
-
Check if the tree is empty:
- If the root is
null, return0as the width.
- If the root is
-
Initialize a queue for level order traversal:
- The queue will store pairs of nodes and their corresponding positions.
-
Add the root node to the queue with position
0. -
Set a variable
maxWidthto0to keep track of the maximum width found. -
While the queue is not empty:
-
Get the number of nodes at the current level (
size). -
Get the minimum position index at this level (
minIndex) to normalize positions. -
Initialize two variables
firstandlastto store the positions of the first and last nodes at this level. -
For each node at the current level:
- Dequeue the node and its position from the queue.
- Normalize the position by subtracting
minIndexfrom thecurrentIndexto avoid overflow issues. - Update
firstwith theindexvalue if it is the first node at this level. - Update
lastwith theindexvalue if it is the last node at this level. - Check if the left child exists:
- Add the left child to the queue with position
2 * current_position.
- Add the left child to the queue with position
- Check if the right child exists:
- Add the right child to the queue with position
2 * current_position + 1.
- Add the right child to the queue with position
-
Calculate the width of the current level as
last - first + 1. -
Update
maxWidthto the maximum of its current value and the width of the current level.
-
-
Return
maxWidthafter processing all levels.
Algorithm Walkthrough
Input: [1, 2, 3, 4, null, null, 5]
Given the binary tree:
1
/ \
2 3
/ \
4 5
Initial Setup:
- Queue:
[(1, 0)](Node1at position0) - maxWidth:
0
Level 1
- Size:
1(Only the root node1) - minIndex:
0(Position of node1) - Initialize
firstandlastto0.
Process Node 1:
- Dequeue Node
1with position0. - Update
firstto0(first node at this level). - Update
lastto0(last node at this level). - Enqueue left child (
2) with position0. - Enqueue right child (
3) with position1. - Calculate Width:
last - first + 1 = 0 - 0 + 1 = 1 - Update maxWidth:
max(0, 1) = 1.
Level 2
- Size:
2(Nodes2and3) - minIndex:
0(Position of node2) - Initialize
firstandlastto0.
Process Node 2:
- Dequeue Node
2with position0. - Update
firstto0(first node at this level). - Enqueue left child (
4) with position0(no right child).
Process Node 3:
- Dequeue Node
3with position1. - Update
lastto1(last node at this level). - Enqueue right child (
5) with position2*index + 1 = 2*1 + 1 = 3(no left child). - Calculate Width:
last - first + 1 = 1 - 0 + 1 = 2 - Update maxWidth:
max(1, 2) = 2.
Level 3
- Size:
2(Nodes4and5) - minIndex:
0(Position of node4) - Initialize
firstandlastto0.
Process Node 4:
- Dequeue Node
4with position0. - Update
firstto0(first node at this level).
Process Node 5:
- Dequeue Node
5with position3. - Update
lastto3(last node at this level). - Calculate Width:
last - first + 1 = 3 - 0 + 1 = 4 - Update maxWidth:
max(2, 4) = 4.
End
- The queue is empty; all levels are processed.
- Return maxWidth:
4.
Final Output: The maximum width of the binary tree is 4.
Code
import java.util.LinkedList;
import java.util.Queue;
// class TreeNode {
// int val;
// TreeNode left;
// TreeNode right;
// // Constructor to create a new tree node
// TreeNode(int x) {
// val = x;
// left = null;
// right = null;
// }
// }
class Pair {
TreeNode node;
int index;
// Constructor to create a new pair
Pair(TreeNode node, int index) {
this.node = node;
this.index = index;
}
}
class Solution {
// Method to find the maximum width of the binary tree
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
Queue<Pair> queue = new LinkedList<>();
queue.offer(new Pair(root, 0)); // Add the root node with position 0
int maxWidth = 0; // Initialize maximum width
// Level order traversal using queue
while (!queue.isEmpty()) {
int size = queue.size();
int minIndex = queue.peek().index; // Get the minimum index at this level to normalize positions
int first = 0, last = 0;
for (int i = 0; i < size; i++) {
Pair current = queue.poll();
TreeNode node = current.node;
int index = current.index - minIndex; // Normalize the index to prevent overflow
// Record the first and last positions at the current level
if (i == 0) first = index;
if (i == size - 1) last = index;
// Enqueue left child with the correct position if it exists
if (node.left != null) {
queue.offer(new Pair(node.left, 2 * index));
}
// Enqueue right child with the correct position if it exists
if (node.right != null) {
queue.offer(new Pair(node.right, 2 * index + 1));
}
}
// Calculate the width of the current level and update maxWidth
maxWidth = Math.max(maxWidth, last - first + 1);
}
return maxWidth;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Create the first example tree
TreeNode example1 = new TreeNode(1);
example1.left = new TreeNode(2);
example1.right = new TreeNode(3);
example1.left.left = new TreeNode(4);
example1.right.right = new TreeNode(5);
// Create the second example tree
TreeNode example2 = new TreeNode(1);
example2.left = new TreeNode(2);
example2.right = new TreeNode(3);
example2.left.left = new TreeNode(4);
example2.left.left.right = new TreeNode(7);
example2.right.left = new TreeNode(5);
example2.right.right = new TreeNode(6);
// Create the third example tree
TreeNode example3 = new TreeNode(1);
example3.left = new TreeNode(2);
example3.left.left = new TreeNode(3);
example3.left.right = new TreeNode(4);
example3.left.right.left = new TreeNode(5);
// Test the widthOfBinaryTree method with the example trees
System.out.println(sol.widthOfBinaryTree(example1)); // Output: 4
System.out.println(sol.widthOfBinaryTree(example2)); // Output: 4
System.out.println(sol.widthOfBinaryTree(example3)); // Output: 2
}
}
Complexity Analys
Time Complexity
- The time complexity of this solution is
, where Nis the total number of nodes in the binary tree. - This is because we perform a level-order traversal (BFS) of the tree, visiting each node exactly once to determine the maximum width.
Space Complexity
- The space complexity is
, where Wis the maximum width of the binary tree. - The space complexity is determined by the maximum number of nodes that could be stored in the queue at any given level of the tree. In the worst case, this will be the width of the widest level of the binary tree.
🤖 Don't fully get this? Learn it with Claude
Stuck on Maximum Width of Binary Tree? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Maximum Width of Binary Tree** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Maximum Width of Binary Tree** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Maximum Width of Binary Tree**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Maximum Width of Binary Tree**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.