Reputation: 23
Please let me know if I am doing anything wrong here.
I am unable to understand the difference between these 2 statements, while finding the height of binary tree.
if (root==NULL) return -1;
and
if (root->left==NULL && root->right==NULL) return 0;
The first statement is giving me accurate result but if I use the second one it is throwing this error "Process returned -1073741819 (0xC0000005) execution time : 2.195 s".
Following is the code :
int bstHeight(bstNode* root)
{
//if (root==NULL) return -1;
//if (root->left==NULL && root->right==NULL) return 0;
else
{
int lh = bstHeight(root->left);
int rh = bstHeight(root->right);
return (lh>rh)? lh+1:rh+1;
}
}
Upvotes: 0
Views: 63
Reputation: 26763
The first one protects against NULL anywhere, in root directly and indirectly via recursion in left and right.
The second is vulnerable against root being NULL, it potentially derferences a NULL, which plausibly gets you the observed error message.
Upvotes: 3