This program finds the maximum height of a binary tree by recursively calculating the height of the left and right subtrees and returning the taller of the two heights plus one. It creates a binary tree with sample nodes, calls the height function on the root node, and prints out the resulting tallest height of the tree, which is 3.
Write a program that finds the max binary tree height. (This is an ex.pdf
1. Write a program that finds the max binary tree height. (This is an extremely short piece of
code!)
Solution
#include
#include
#include
typedef struct node
{
int info;
struct node *left;
struct node *right;
}node;
node *newNode(int data)
{
node *ptr=(node *)malloc(sizeof(node));
ptr->info=data;
ptr->left=NULL;
ptr->right=NULL;
return ptr;
}
int height(node *root)
{
if(root==NULL)
return 0;
int l=height(root->left);
int m=height(root->right);
if(l>m)
return l+1;
else
return m+1;
}
int main()
2. {
struct node *root1 = newNode(1);
root1->left = newNode(2);
root1->right = newNode(3);
root1->left->left = newNode(4);
root1->left->right = newNode(5);
int m=height(root1);
printf("Height of the tree is :- %d",m);
getch();
return 0;
}