Find binary tree height
13,810
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.
Author by
MRBULL93
Updated on June 04, 2022Comments
-
MRBULL93 almost 2 years
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--; } }