Find binary tree height

binary-tree, c++, tree

Solution

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.

Problem

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--; } } ```

Original source