The runtime error you're encountering is due to the indices (idx) growing too large, causing a signed integer overflow when calculating 2 * idx + 1 or 2 * idx + 2. This typically happens in very deep binary trees where the index values can become extremely large.
To fix this issue without significantly altering your original code, you can normalize the indices at each level by subtracting the leftmost index of the current level from all indices. This ensures that the indices remain manageable and prevents overflow.
Here's the corrected code with the necessary modification:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if (!root) return 0; // Handle empty tree
queue<pair<TreeNode*, long long>> q;
q.push({root, 0});
long long maxw = 0;
while(!q.empty()){
long long l = q.front().second; // Leftmost index of current level
long long r = q.back().second; // Rightmost index of current level
// Update maximum width
maxw = max(maxw, r - l + 1);
int n = q.size();
while(n--){
TreeNode* curr = q.front().first;
long long idx = q.front().second - l; // Normalize index
q.pop();
// Push left child with normalized index
if(curr->left){
q.push({curr->left, 2 * idx + 1});
}
// Push right child with normalized index
if(curr->right){
q.push({curr->right, 2 * idx + 2});
}
}
}
return maxw;
}
};
Explanation of the Changes:
-
Normalization of Indices:
- Before:
q.push({curr->left, 2*idx + 1});
- After:
q.push({curr->left, 2*(idx - l) + 1});
By subtracting l (the leftmost index of the current level) from idx, you ensure that the indices start from 0 at each level. This prevents the indices from growing exponentially large, thereby avoiding overflow.
-
Handling Empty Trees:
- Added a check at the beginning to return
0 if the root is nullptr, ensuring the function handles empty trees gracefully.
Why This Works:
- Preventing Overflow: By resetting the base index
l for each level, the relative indices remain small, preventing the multiplication 2 * idx from exceeding the long long range.
- Maintaining Correct Width Calculation: The width is still correctly calculated as the difference between the rightmost and leftmost indices plus one (
r - l + 1), ensuring the result remains accurate.
This minimal change effectively resolves the overflow issue while preserving the original logic of your solution.