Maximum Width of Binary Tree in DSA C++ - Time & Space Complexity
We want to know how the time needed to find the maximum width of a binary tree changes as the tree grows.
How does the number of nodes affect the work done?
Analyze the time complexity of the following code snippet.
int widthOfBinaryTree(TreeNode* root) {
if (!root) return 0;
unsigned long long maxWidth = 0;
queue> q;
q.push({root, 0});
while (!q.empty()) {
int size = q.size();
unsigned long long start = q.front().second;
unsigned long long end = q.back().second;
maxWidth = max(maxWidth, end - start + 1);
for (int i = 0; i < size; i++) {
auto node = q.front().first;
unsigned long long idx = q.front().second - start;
q.pop();
if (node->left) q.push({node->left, 2 * idx + 1});
if (node->right) q.push({node->right, 2 * idx + 2});
}
}
return (int)maxWidth;
}
This code finds the maximum width of a binary tree by level-order traversal, tracking positions to measure width.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop runs once per level of the tree, and inside it, a for loop processes all nodes at that level.
- How many times: Each node is visited exactly once during the traversal.
As the number of nodes (n) grows, the code visits each node once, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and checks |
| 100 | About 100 visits and checks |
| 1000 | About 1000 visits and checks |
Pattern observation: The operations increase linearly as the tree size increases.
Time Complexity: O(n)
This means the time to find the maximum width grows directly with the number of nodes in the tree.
[X] Wrong: "The time depends on the height of the tree only because we process level by level."
[OK] Correct: Even though we go level by level, every node is visited once, so the total work depends on the total number of nodes, not just the height.
Understanding how to analyze level-order traversal helps you explain many tree problems clearly and confidently in interviews.
"What if we used a depth-first search instead of a breadth-first search? How would the time complexity change?"
Practice
Solution
Step 1: Understand the term 'width' in a tree
The width of a binary tree at a level is the count of nodes present at that level.Step 2: Define 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
- Counting total nodes instead of per level
- Summing node values instead of counting nodes
Solution
Step 1: Understand queue declaration with pairs
To store pairs, use std::pair with template parameters inside std::queue<>.Step 2: Check syntax correctness
std::queue> q; correctly uses std::queue> q; which is valid C++ syntax.Final Answer:
std::queue> q; -> Option DQuick Check:
Queue of pairs syntax = std::queue> [OK]
- Missing std::pair<> inside queue
- Incorrect template syntax
- Omitting std:: prefix
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Tree structure:
// 1
// / \
// 2 3
// / \
// 4 5
int maxWidth(TreeNode* root) {
if (!root) return 0;
std::queue> q;
q.push({root, 0});
int maxWidth = 0;
while (!q.empty()) {
int size = q.size();
int start = q.front().second;
int end = start;
for (int i = 0; i < size; i++) {
auto [node, idx] = q.front(); q.pop();
end = idx;
if (node->left) q.push({node->left, 2 * idx + 1});
if (node->right) q.push({node->right, 2 * idx + 2});
}
maxWidth = std::max(maxWidth, end - start + 1);
}
return maxWidth;
}
// Call: maxWidth(root);Solution
Step 1: Analyze tree levels and node indices
Level 0: Node 1 at index 0 (width = 1) Level 1: Nodes 2 (1), 3 (2) width = 2 Level 2: Nodes 4 (3), 5 (6) width = 6 - 3 + 1 = 4Step 2: Calculate maximum width using code logic
Code calculates width as end - start + 1 per level. Level 2 width is 4, which is maximum.Final Answer:
4 -> Option CQuick Check:
Max width = 4 nodes at level 2 [OK]
- Counting nodes without index gaps
- Ignoring index-based width calculation
- Assuming width equals node count only
int widthOfBinaryTree(TreeNode* root) {
std::queue> q;
q.push({root, 0});
int maxWidth = 0;
while (!q.empty()) {
int size = q.size();
int start = q.front().second;
int end = q.back().second;
maxWidth = std::max(maxWidth, end - start + 1);
for (int i = 0; i < size; i++) {
auto [node, idx] = q.front(); q.pop();
if (node->left) q.push({node->left, 2 * idx + 1});
if (node->right) q.push({node->right, 2 * idx + 2});
}
}
return maxWidth;
}Solution
Step 1: Analyze the width calculation timing
The code calculates width using q.back().second before popping nodes in the current level.Step 2: Identify the bug
Since q.back() includes nodes from the next level (pushed during previous iteration), width calculation is incorrect.Final Answer:
Using q.back().second before popping nodes causes incorrect width calculation -> Option BQuick Check:
Calculate width after popping all nodes at current level [OK]
- Forgetting root null check
- Misplacing width calculation inside loop
- Wrong child index formulas
Solution
Step 1: Understand the problem with missing nodes
Missing nodes create gaps, so counting nodes alone misses true width.Step 2: Use indices to track node positions
Assign indices to nodes as if in a full binary tree to capture gaps, then width = end - start + 1.Final Answer:
Use level order traversal with node indices to track positions and calculate width as end - start + 1 -> Option AQuick Check:
Index-based width handles gaps correctly [OK]
- Ignoring gaps by counting nodes only
- Using node values instead of positions
- Using DFS without position tracking
Ready to prove it?
Pass the test and this pattern moves unknown
