-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeight Balanced BST
98 lines (87 loc) · 1.88 KB
/
Height Balanced BST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
Implement a C program to find whether a given Binary Search Tree is height balanced
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct tnode
{
int data;
struct tnode * leftc;
struct tnode * rightc;
};
void insert(struct tnode **, int num);
void inorder(struct tnode *);
int height(struct tnode* node);
int isBalanced(struct tnode *root);
int max(int a, int b);
int main()
{
struct tnode * root=NULL;
char ch[5];
int num;
do
{
printf("Enter the element to be inserted in the tree\n");
scanf("%d",&num);
insert(&root, num);
printf("Do you want to insert another element?\n");
scanf("%s",ch);
}while(strcmp(ch,"yes")==0);
printf("The elements in the tree are");
inorder(root);
printf("\n");
if(isBalanced(root))
printf("The tree is height balanced\n");
else
printf("The tree is not height balanced\n");
return 0;
}
void insert(struct tnode ** s, int num)
{
if((*s) == NULL)
{
(*s) = (struct tnode *) malloc( sizeof (struct tnode));
(*s)->data = num;
(*s)->leftc = NULL;
(*s)->rightc = NULL;
}
else
{
if(num < (*s)->data)
insert(&( (*s)->leftc ), num);
else
insert(&( (*s)->rightc ), num);
}
}
void inorder(struct tnode * s)
{
if(s!=NULL){
inorder(s->leftc);
printf(" %d",s->data);
inorder(s->rightc);
}
}
/* Returns true if binary tree with root as root is height-balanced */
int isBalanced(struct tnode *root)
{
if(root == NULL){
return 1;
}
int lh=height(root->leftc);
int rh = height(root->rightc);
if(abs(lh-rh)<=1 && (isBalanced(root->leftc)&&isBalanced(root->rightc)))
return 1;
return 0;
}
/* The function Compute the "height" of a tree. Height is the
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct tnode* node)
{
if(node==NULL)
return 0;
return 1+ max(height(node->leftc),height(node->rightc));
}
int max(int a, int b)
{
return (a >= b)? a: b;
}