I am trying to write a function to get the height of a binary tree. When I print the value of the maxi the value is what I expect but when the function returns the value, the value is always 0. Can someone tell what I am doing wrong here?
int treeHeight(tree *p)
{
static int maxi=0;
static int i=0;
if(p==NULL)
{
return maxi;
}
else
{
if(p->left!=NULL||p->right!=NULL)
{
i++;
}
else
{
i++;
if(maxi<i)
{
maxi=i;
}
}
treeHeight(p->left);
treeHeight(p->right);
i--;
}
}
Your treeHeight function should look like the following:
int treeHeight(tree *p)
{
if (p == NULL)
{
return -1;
}
int left = treeHeight(p->left);
int right = treeHeight(p->right);
return 1 + std::max(left, right);
}
Why do you need to static variables i and maxi there? You don't need those variables there to find out the height of a binary tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With