Maximum Width of Binary Tree in DSA Java - Time & Space Complexity
We want to understand how the time needed to find the maximum width of a binary tree changes as the tree grows.
Specifically, how does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
public int widthOfBinaryTree(TreeNode root) {
if (root == null) return 0;
Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
queue.offer(new Pair<>(root, 0));
int maxWidth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
int minIndex = queue.peek().getValue();
int first = 0, last = 0;
for (int i = 0; i < size; i++) {
Pair<TreeNode, Integer> p = queue.poll();
TreeNode node = p.getKey();
int index = p.getValue() - minIndex;
if (i == 0) first = index;
if (i == size - 1) last = index;
if (node.left != null) queue.offer(new Pair<>(node.left, 2 * index + 1));
if (node.right != null) queue.offer(new Pair<>(node.right, 2 * index + 2));
}
maxWidth = Math.max(maxWidth, last - first + 1);
}
return maxWidth;
}
This code finds the maximum width of a binary tree by level-order traversal, tracking node positions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that visits each level of the tree and the inner for loop that processes each node at that level.
- How many times: Each node in the tree is visited exactly once during the traversal.
As the number of nodes (n) increases, the code visits each node once, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits to nodes |
| 100 | About 100 visits to nodes |
| 1000 | About 1000 visits to nodes |
Pattern observation: The operations increase linearly as the tree size grows.
Time Complexity: O(n)
This means the time to find the maximum width grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The time complexity is O(width) because we only process nodes level by level."
[OK] Correct: Even though we process nodes level by level, every node in the tree is visited once, so the total work depends on the total number of nodes, not just the width.
Understanding how tree traversals scale helps you explain your approach clearly and shows you can reason about efficiency, a key skill in coding interviews.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of width in a binary tree
The width is the count of nodes at a particular level in the tree.Step 2: Identify maximum width
The maximum width is the largest such count among all levels.Final Answer:
The largest number of nodes present at any single level of the tree -> Option AQuick Check:
Maximum width = max nodes at any level [OK]
- Confusing width with tree height
- Thinking width is sum of node values
- Counting total nodes instead of per level
Solution
Step 1: Identify traversal method for level order
Level order traversal uses a queue to process nodes level by level.Step 2: Choose data structure
A queue allows nodes to be added and removed in FIFO order, perfect for level traversal.Final Answer:
Queue -> Option CQuick Check:
Level order traversal uses queue [OK]
- Using stack which is LIFO, not suitable for level order
- Choosing HashMap which doesn't preserve order
- Using ArrayList without queue behavior
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) { val = v; }
}
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.right = new TreeNode(5);
// Maximum width calculation
int maxWidth = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
maxWidth = Math.max(maxWidth, size);
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
System.out.println(maxWidth);Solution
Step 1: Analyze tree levels and node counts
Level 1 has 1 node (1), level 2 has 2 nodes (2,3), level 3 has 2 nodes (4,5).Step 2: Determine maximum width
The maximum number of nodes at any level is 2.Final Answer:
2 -> Option BQuick Check:
Max width = 2 nodes at level 2 [OK]
- Counting total nodes instead of per level
- Assuming level 3 has 3 nodes incorrectly
- Ignoring null children in width calculation
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int maxWidth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
maxWidth = Math.max(maxWidth, size);
for (int i = 0; i <= size; i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}Solution
Step 1: Check the for loop iteration count
The loop runs from i = 0 to i <= size, which means it runs size+1 times, causing an extra poll.Step 2: Correct the loop condition
It should run exactly size times, so condition must be i < size.Final Answer:
The loop condition should be i < size, not i <= size -> Option AQuick Check:
Loop must run size times exactly [OK]
- Using <= instead of < in for loop
- Replacing queue with stack incorrectly
- Updating maxWidth at wrong place
Solution
Step 1: Understand the problem with missing nodes
Simple counting misses gaps caused by null children, so width is underestimated.Step 2: Use indexing to simulate complete tree positions
Assign indices to nodes as in a complete binary tree (root=0, left=2*index, right=2*index+1).Step 3: Calculate width per level using min and max indices
Width = max index - min index + 1, capturing gaps between nodes.Final Answer:
Assign an index to each node as if the tree was a complete binary tree, track min and max indices per level, width = max - min + 1 -> Option DQuick Check:
Indexing nodes captures gaps for accurate width [OK]
- Ignoring null gaps between nodes
- Counting only non-null nodes without positions
- Using stack instead of queue for level traversal
Ready to prove it?
Pass the test and this pattern moves unknown
