Maximum Width of Binary Tree solution and explanation
9 more videos on this problem
L28. Maximum Width of Binary Tree | C++ | Javatake U forward · 22:41 · 469K views
Maximum Width of Binary Tree - Leetcode 662 - PythonNeetCodeIO · 11:38 · 32K views
Maximum Width of Binary Tree | Leetcode 662 | Flipkart | Amazon | Explanation | Live CodecodestorywithMIK · 16:53 · 23K views
Maximum Width of Binary Tree | LeetCode 662 | C++, PythonKnowledge Center · 22:26 · 14K views
Maximum Width of Binary Tree | Leetcode 662| Binary Tree | Day-27Ayushi Sharma · 18:44 · 8K views
Maximum Width of Binary Tree - LeetCode 662 - PythonDeepti Talesra · 13:54 · 2K views
Maximum Width of Binary Tree | LeetCode 662 | Programming TutorialsProgramming Tutorials · 16:22 · 2K views
Maximum Width of Binary Tree | Leetcode 662 (Java Solution Explained)The Tech Granth · 11:52 · 1K views
Maximum Width of Binary Tree - LeetCode 662 - Python SolutionCode with Carter · 12:05 · 458 views
LeetCode Maximum Width of a Binary Tree Explained - JavaNick White · 12:21 · 36K views
The problem
Given the root of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (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.
It is guaranteed that the answer will in the range of a 32-bit signed integer.
Example 1:
Input: root = [1,3,2,5,3,null,9] Output: 4 Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).
Example 2:
Input: root = [1,3,2,5,null,null,9,6,null,7] Output: 7 Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).
Example 3:
Input: root = [1,3,2,5] Output: 2 Explanation: The maximum width exists in the second level with length 2 (3,2).
Constraints:
- The number of nodes in the tree is in the range
[1, 3000]. -100 <= Node.val <= 100
Approach overview
Problem Overview: You are given the root of a binary tree. The width of a level is defined as the distance between the leftmost and rightmost non-null nodes, counting the null positions that would exist in a complete binary tree. The task is to compute the maximum width across all levels.
Approach 1: Level Order Traversal with Position Tracking (O(n) time, O(n) space)
This approach performs a standard Breadth-First Search using a queue. Each node is assigned a positional index as if the tree were stored in an array representation of a complete binary tree. The root starts at index 0, the left child gets 2*i, and the right child gets 2*i + 1. For every level, record the index of the first and last node in the queue. The width of that level is last_index - first_index + 1. The algorithm iterates level by level, updating the maximum width seen so far.
This works because positional indices preserve the virtual gaps between nodes that would appear in a complete tree layout. Even if some nodes are missing, the index difference still captures the correct width. Since each node is processed exactly once, the traversal runs in O(n) time with O(n) queue space in the worst case.
Approach 2: DFS with Position Tracking (O(n) time, O(h) space)
A Depth-First Search can compute the same width by tracking the first index encountered at every depth. Traverse the binary tree recursively while passing two values: the current depth and the node's positional index. When visiting a depth for the first time, store that index as the leftmost position for that level. For every node visited later at the same depth, compute the width using current_index - first_index_at_depth + 1.
This approach avoids storing entire levels like BFS. Instead, it only stores the first index for each depth and relies on recursion to explore the tree. The maximum width is updated during traversal. Because each node is visited once, the time complexity remains O(n). Space complexity becomes O(h) for recursion depth, where h is the tree height (up to O(n) in skewed trees).
Recommended for interviews: The level-order BFS approach is the most common interview solution. It clearly demonstrates understanding of tree traversal and how to simulate complete-tree indexing. The DFS variant shows deeper insight and uses less auxiliary memory when the tree height is small. Showing BFS first and then mentioning DFS as an optimization signals strong problem-solving depth.
Approach 1: Level Order Traversal with Position Tracking
To solve the problem, we can perform a level order traversal (breadth-first search) of the tree using a queue. Each node will be annotated with a position value, starting with the root being assigned the position 0. As we traverse each level, we calculate the width as the difference between the position of the last node and the first node of that level plus one. This approach ensures that we take into account null positions that would exist in a perfect binary tree.
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
queue = deque([(root, 0)])
max_width = 0
while queue:
level_length = len(queue)
_, first_pos = queue[0]
for i in range(level_length):
node, pos = queue.popleft()
if node.left:
queue.append((node.left, 2 * pos))
if node.right:
queue.append((node.right, 2 * pos + 1))
_, last_pos = queue[-1] if queue else (None, 0)
max_width = max(max_width, last_pos - first_pos + 1)
return max_widthimport java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
Deque<Pair<TreeNode, Integer>> queue = new ArrayDeque<>();
queue.add(new Pair<>(root, 0));
int maxWidth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
int firstPos = queue.getFirst().getValue();
int lastPos = firstPos; // initialize to avoid lastPos not being set
for (int i = 0; i < size; i++) {
Pair<TreeNode, Integer> pair = queue.poll();
TreeNode node = pair.getKey();
int pos = pair.getValue();
if (node.left != null) {
queue.add(new Pair<>(node.left, 2 * pos));
}
if (node.right != null) {
queue.add(new Pair<>(node.right, 2 * pos + 1));
}
lastPos = pos;
}
maxWidth = Math.max(maxWidth, lastPos - firstPos + 1);
}
return maxWidth;
}
}
class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}This Python solution uses a queue to perform a level order traversal. Each node's position is calculated by multiplying its parent position by 2 and adding 1 for right children. The width of each level is calculated using the positions assigned to each node.
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is processed exactly once.
Space Complexity: O(w), where w is the maximum width of the tree, held in the queue at any level.
Approach 2: DFS with Position Tracking
An alternative approach involves using depth-first search (DFS) to traverse the tree while maintaining a map of the first position of each level. By keeping track of each node’s depth and position, we can determine the width of any tree level by computing the difference between the first and the current node's position at that depth.
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
def dfs(node, depth, position, first_pos_map):
nonlocal max_width
if node is None:
return
if depth not in first_pos_map:
first_pos_map[depth] = position
max_width = max(max_width, position - first_pos_map[depth] + 1)
dfs(node.left, depth + 1, 2 * position, first_pos_map)
dfs(node.right, depth + 1, 2 * position + 1, first_pos_map)
max_width = 0
first_pos_map = {}
dfs(root, 0, 0, first_pos_map)
return max_width#include <unordered_map>
#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
unsigned long long maxWidth = 0;
std::unordered_map<int, unsigned long long> firstPosMap;
dfs(root, 0, 0, firstPosMap, maxWidth);
return maxWidth;
}
private:
void dfs(TreeNode* node, int depth, unsigned long long position,
std::unordered_map<int, unsigned long long>& firstPosMap, unsigned long long& maxWidth) {
if (!node) return;
if (!firstPosMap.count(depth)) {
firstPosMap[depth] = position;
}
maxWidth = std::max(maxWidth, position - firstPosMap[depth] + 1);
dfs(node->left, depth + 1, 2 * position, firstPosMap, maxWidth);
dfs(node->right, depth + 1, 2 * position + 1, firstPosMap, maxWidth);
}
};This Python solution implements DFS to visit each node, mapping each level's first node position. We calculate width by comparing the position of the current node to this first node's position at each level.
Time Complexity: O(n), visiting each node recursively.
Space Complexity: O(d), where d is the max depth of the tree, accounting for the recursion stack.
Approach 3: Default Approach
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func widthOfBinaryTree(root *TreeNode) int {
q := []pair{{root, 1}}
ans := 0
for len(q) > 0 {
ans = max(ans, q[len(q)-1].i-q[0].i+1)
for n := len(q); n > 0; n-- {
p := q[0]
q = q[1:]
root = p.node
if root.Left != nil {
q = append(q, pair{root.Left, p.i << 1})
}
if root.Right != nil {
q = append(q, pair{root.Right, p.i<<1 | 1})
}
}
}
return ans
}
type pair struct {
node *TreeNode
i int
}Complexity comparison
| Approach | Complexity |
|---|---|
| Level Order Traversal with Position Tracking | Time Complexity: O(n), where n is the number of nodes in the tree, as each node is processed exactly once. Space Complexity: O(w), where w is the maximum width of the tree, held in the queue at any level. |
| DFS with Position Tracking | Time Complexity: O(n), visiting each node recursively. Space Complexity: O(d), where d is the max depth of the tree, accounting for the recursion stack. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Level Order Traversal with Position Tracking (BFS) | O(n) | O(n) | Best general solution. Easy to reason about because width is computed level by level. |
| DFS with Position Tracking | O(n) | O(h) | Useful when avoiding large queues. Works well when tree height is relatively small. |
Frequently asked questions
Is Maximum Width of Binary Tree easy or hard?
Maximum Width of Binary Tree is considered a medium-level problem. The tree traversal itself is straightforward, but the challenge comes from correctly tracking positions to account for gaps between nodes.
Maximum Width of Binary Tree Python/Java solution
Both Python and Java implementations typically use a queue storing pairs of (node, index). For each level, track the first and last index and update the maximum width. The same indexing logic works across languages and maintains O(n) time complexity.
How to solve Maximum Width of Binary Tree in O(n)?
Traverse the tree while assigning indices that mimic a complete binary tree layout. During BFS, track the first and last index at each level and compute width using their difference. Because every node is processed once, the algorithm achieves O(n) time complexity.
What is the best approach for Maximum Width of Binary Tree?
The most common solution uses level order traversal (BFS) with positional indexing. Each node is assigned an index similar to a complete binary tree representation, allowing you to compute width as last_index - first_index + 1 for each level. This approach runs in O(n) time and O(n) space.
Is Maximum Width of Binary Tree asked at Google/Amazon/Meta?
Binary tree traversal and width-related problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variations of this problem test understanding of BFS, DFS, and how tree nodes map to array-style indexing.
What data structure is used in Maximum Width of Binary Tree?
The main data structure is a queue for breadth-first traversal. Each queue entry stores a tree node along with its positional index. In the DFS version, recursion and a hash map or array store the first index encountered at each depth.
What is the time complexity of Maximum Width of Binary Tree?
The optimal solutions run in O(n) time where n is the number of nodes in the tree. Each node is visited exactly once during traversal. Space complexity is O(n) for the BFS queue or O(h) for the DFS recursion stack, where h is the height of the tree.
