Program to find the maximum Height of a Binary Tree

Maximum Height of binary tree is the maximum number of nodes between the root node and the farthest leaf node which could be in either left or right subtree of Binary tree.


Program :


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>


struct node
{
    int data;
    struct node* left;
    struct node* right;
};


int maxheight(struct node* node)
{
   if (node==NULL)
       return 0;
   else
   {
     
       int l = maxheight(node->left);        /*Recursively travel till you reach the farthest node on left
       int r = maxheight(node->right);     /*Recursively travel till you reach the farthest node on Right

       if (l>r)
           return(l+1);                             /* if l>r it means there are more number of nodes in left then right so    
                                                           return (l+1) including root node.
       else
           return(r+1);                            /* otherwise return (r+1)
   }
}


struct node* EnterNode(int data)
{
    struct node* node = (node*)malloc(sizeof(node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return(node);
}
 
int main()
{
    struct node *root = EnterNode(10);

    root->left = EnterNode(5);
    root->right = EnterNode(20);
    root->left->left = EnterNode(4);
    root->left->right = EnterNode(8);
 
    printf("Max height of tree is %d", maxheight(root));
 
    getch();
}


Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Number series arrangement puzzles