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?"