Write a C function to find the height or depth of a tree.

Write a C function to find the height or depth of a tree.

Solution : The height can be found out recursively by calculating height of left sub tree tree and right sub tree.Height of tree would be the maximum  of height of left subtree and height of right subtree + 1.

 

int heightofTree(struct node *root)
{
   int lheight,rheight;
   if(root==NULL)
      return 0;
   if(root->left)
      lheight = heightofTree(root->left);
   if(root->right)
      rheight = heightofTree(root->right);
   return(max(lheight,rheight)+1);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation