I am working on a code challenge where I need to find the number of nodes in a complete binary tree. The number of nodes is at most 50000.
When I submitted the code below, the evaluator reported an "int overflow error" on the statement ans += (1 << depth).
My question
Given the maximum number of nodes, I'd think the depth of the tree is at most 16, and the value of depth should not reach 32. So then why do I get an int overflow error?
My code
/**
* 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 countNodes(TreeNode* root) {
if(root == nullptr) return 0;
queue<TreeNode*> que;
int depth = 0;
que.push(root);
long ans = 0;
while(!que.empty())
{
depth++;
int size = que.size();
for(int i = 0; i < size; i++)
{
TreeNode* node = que.front();
if(!node->left)
{
if(!i) ans += (1 << depth);
else ans += (1 << depth) + (1 << i);
break;
}
else que.push(node->left);
if(!node->right)
{
if(!i) ans += (1 << depth) + 1;
else ans += (1 << depth) + (1 << i) + 1;
break;
}
else que.push(node->right);
que.pop();
}
}
return ans;
}
};