Difference b/w these 2 statements while finding height of binary tree?


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;  


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;

        int lh = bstHeight(root->left);
        int rh = bstHeight(root->right);
        return (lh>rh)? lh+1:rh+1;
asked on Stack Overflow Feb 5, 2021 by spoiicy • edited Feb 5, 2021 by Yunnosch

1 Answer


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.

answered on Stack Overflow Feb 5, 2021 by Yunnosch

User contributions licensed under CC BY-SA 3.0