Code calculates width as end - start + 1 per level.
Level 2 width is 4, which is maximum.
Final Answer:
4 -> Option C
Quick Check:
Max width = 4 nodes at level 2 [OK]
Hint: Track indices per level, width = end - start + 1 [OK]
Common Mistakes:
Counting nodes without index gaps
Ignoring index-based width calculation
Assuming width equals node count only
4. Identify the bug in the following code snippet that attempts to compute the maximum width of a binary tree:
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;
}
medium
A. Not checking if root is nullptr before processing
B. Using q.back().second before popping nodes causes incorrect width calculation
C. Incorrect indexing formula for child nodes
D. Missing return statement at the end
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 B
Quick Check:
Calculate width after popping all nodes at current level [OK]
Hint: Calculate width after processing current level nodes [OK]
Common Mistakes:
Forgetting root null check
Misplacing width calculation inside loop
Wrong child index formulas
5. You want to find the maximum width of a binary tree that may have missing nodes between left and right children at some levels. Which approach correctly handles gaps caused by missing nodes?
hard
A. Use level order traversal with node indices to track positions and calculate width as end - start + 1
B. Count only the number of nodes at each level ignoring their positions
C. Calculate width as the difference between maximum and minimum node values at each level
D. Use depth-first traversal and count nodes recursively without indices