#include <stdio.h>
#include <stdlib.h>
// Definition 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 find the height of a tree.
// Returns -1 if the tree is unbalanced.
int height(struct Node* root) {
// An empty tree has a height of 0.
if (root == NULL)
return 0;
// Get the height of the left and right subtrees.
int leftHeight = height(root->left);
int rightHeight = height(root->right);
// If left or right subtree is unbalanced, return -1.
if (leftHeight == -1 || rightHeight == -1)
return -1;
// If the difference in height between left and right subtrees is more than 1, return -1.
if (abs(leftHeight - rightHeight) > 1)
return -1;
// Otherwise, return the height of the tree.
return 1 + (leftHeight > rightHeight ? leftHeight : rightHeight);
}
// Function to check if the tree is balanced.
int isBalanced(struct Node* root) {
return height(root) != -1;
}
// Main function to test the above functions.
int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->left->left->left = createNode(8);
if (isBalanced(root))
printf("The binary tree is balanced.\n");
else
printf("The binary tree is not balanced.\n");
return 0;
}
Explanation of the Code:
- Node Structure:
struct Node
represents a node of the binary tree, containing:data
: Value stored in the node.left
: Pointer to the left child.right
: Pointer to the right child.
- Create Node:
createNode(int data)
allocates memory for a new node and initializes it with the given value, setting its left and right pointers toNULL
.
- Height Calculation:
height(struct Node* root)
calculates the height of a subtree rooted atroot
.- It recursively finds the heights of the left and right subtrees.
- If any subtree is unbalanced or the height difference exceeds 1, it returns
-1
. - Otherwise, it returns the height of the current subtree.
- Check for Balanced Tree:
isBalanced(struct Node* root)
checks if the binary tree is balanced by callingheight()
.- If the height function returns
-1
, it means the tree is unbalanced; otherwise, it is balanced.
- Main Function:
- Constructs a sample tree and checks if it is balanced.
- The output is printed based on whether the tree is balanced.
Output:
For the given sample tree:
1
/ \
2 3
/ \
4 5
/
8
The output would be:
The binary tree is not balanced.
Explanation of Output:
- In this case, the left subtree of
2
(which includes4
and8
) is deeper than its right subtree. - The height difference between the left and right subtrees of
2
is more than 1. - Therefore, the tree is identified as unbalanced.