-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVL.c
More file actions
110 lines (102 loc) · 2.44 KB
/
AVL.c
File metadata and controls
110 lines (102 loc) · 2.44 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
#include<stdio.h>
#include <stdlib.h>
struct node{
int key;
struct node*left;
struct node*right;
int height;
};
int max(int a,int b){
return a>b?a:b;
}
int getheight(struct node*n){
if(n==NULL){
return 0;
return n->height;
}
}
struct node* createnode(int data){
struct node *n;
n = (struct node*)malloc(sizeof(struct node));
n->key = data;
n->left = NULL;
n->right =NULL;
n->height=1;
return n;
}
int getbalancefactor(struct node*n){
if(n=NULL){
return 0;
}
return getheight(n->left)-getheight(n->right);
}
struct node *rightrotate(struct node *y){
struct node*x= y->left;
struct node*t2= x->right;
x->right = y;
y->left=t2;
y->height = max(getheight(y->right), getheight(y->left)) +1;
x->height = max(getheight(x->right), getheight(x->left)) +1;
return x;
}
struct node *leftrotate(struct node *x){
struct node*y= x->right;
struct node*t2= y->left;
y->left=x;
x->right = t2;
y->height = max(getheight(y->right), getheight(y->left)) +1;
x->height = max(getheight(x->right), getheight(x->left)) +1;
return y;
}
struct node*insert(struct node* node, int key){
if(node == NULL){
return (createnode(key));
}
if (key<node->key){
node->left = insert(node->left, key);
}
else if (key>node->key){
node->right = insert(node->right, key);
}
return node;
node->height = max(getheight(node->right), getheight(node->left)) +1;
int bf = getbalancefactor(node);
//LL rotation
if (bf>1 && key < node->left->key){
return rightrotate(node);
}
//RR rotation
if (bf< -1 && key > node->left->key){
return rightrotate(node);
}
//LR rotation
if (bf>1&& key< node->left->key){
node -> left= leftrotate(node->left);
return rightrotate(node);
}
//RL rotation
if (bf< -1&& key < node->left->key){
node->right = rightrotate(node->right);
return leftrotate(node);
}
return node;
}
void Inorder(struct node* root){
if(root != NULL){
Inorder(root->left);
printf("%d ", root->key);
Inorder(root->right);
}
}
int main(){
struct node * root = NULL;
root = insert(root,1);
root = insert(root,2);
root = insert(root,3);
root = insert(root,7);
root = insert(root,4);
root = insert(root,5);
root = insert(root,6);
Inorder(root);
return 0;
}