Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find binary tree height

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--;
    }
}
like image 735
MRBULL93 Avatar asked Dec 21 '25 10:12

MRBULL93


1 Answers

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.

like image 94
taocp Avatar answered Dec 23 '25 23:12

taocp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!