#include <stdio.h>
#include <stdlib.h>
// Structure for a binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to calculate the height of the binary tree
int height(struct Node* root) {
if (root == NULL) {
return -1;
}
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
int main() {
// Creating the binary tree
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
// Calculating the height of the tree
int treeHeight = height(root);
printf("Height of the binary tree is: %d\n", treeHeight);
return 0;
}
Explanation
- Node Creation: The
createNode
function allocates memory for a new node and initializes itsdata
field with the given value. Theleft
andright
pointers are set toNULL
. - Building the Tree: We manually create a binary tree with the following structure:
1
/ \
2 3
/ \ / \
4 5 6 7
Height Calculation: The height
function calculates the height of the tree recursively by determining the maximum height between the left and right subtrees and adding 1 for the root node.Output: The main
function calculates the height of the binary tree and prints it.
Output
When you run the program, it will display:
Height of the binary tree is: 2
Explanation of the Output
- The height of the tree is
2
because:- Nodes
4
,5
,6
, and7
are at level2
. - Nodes
2
and3
are at level1
. - The root node
1
is at level0
.
- Nodes
- The longest path from the root to a leaf node is of length
2
(e.g.,1 -> 2 -> 4
).