This program computes the diameter of a binary tree, which is the longest path between any two nodes in the tree. This path may or may not pass through the root.
Program Explanation
The program includes:
- Node Structure: Defines the structure of each node in the binary tree.
- Utility Function to Create a Node: Helps in creating a new tree node.
- Recursive Function to Calculate Diameter: Recursively calculates the height of each subtree while updating the maximum diameter found so far.
- Main Function: Creates a sample binary tree and finds its diameter.
Program Code
// Include necessary headers
#include <stdio.h>
#include <stdlib.h>
// Define the structure for tree nodes
typedef struct node {
int data;
struct node* left;
struct node* right;
} Node;
// Function to create a new tree node
Node* newNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// Utility function to calculate the height of the binary tree
int height(Node* node) {
if (node == NULL)
return 0;
int leftHeight = height(node->left);
int rightHeight = height(node->right);
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
// Function to calculate the diameter of the binary tree
int diameter(Node* node) {
if (node == NULL)
return 0;
// Get the height of left and right sub-trees
int leftHeight = height(node->left);
int rightHeight = height(node->right);
// Get the diameter of left and right sub-trees
int leftDiameter = diameter(node->left);
int rightDiameter = diameter(node->right);
// Return max of left/right subtree diameters or the path that goes through the root
return max(leftDiameter, max(rightDiameter, leftHeight + rightHeight + 1));
}
// Helper function to find the maximum of two integers
int max(int a, int b) {
return a > b ? a : b;
}
// Main function
int main() {
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("The diameter of the given binary tree is %d\\n", diameter(root));
return 0;
}
Key Components of the Program:
- Node Structure: Represents each node in the binary tree.
- newNode Function: Allocates memory and initializes a new node.
- height Function: Calculates the height of the tree from a given node, which is used to determine the path length involving this node’s subtrees.
- diameter Function: Calculates the diameter recursively by comparing the longest path that might either go through the root of the subtree or only involve one of its sides.
- max Function: A utility to compute the maximum of two integers, used in comparing path lengths.
- Main Function: Sets up a sample binary tree, computes its diameter using the
diameter
function, and outputs the result.
This program is structured to clearly separate concerns: node creation, tree height calculation, diameter computation, and the main execution logic, which aids in maintainability and readability.