#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

  1. Node Creation: The createNode function allocates memory for a new node and initializes its data field with the given value. The left and right pointers are set to NULL.
  2. 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, and 7 are at level 2.
    • Nodes 2 and 3 are at level 1.
    • The root node 1 is at level 0.
  • The longest path from the root to a leaf node is of length 2 (e.g., 1 -> 2 -> 4).

Leave a Reply

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

Verified by MonsterInsights