-
Notifications
You must be signed in to change notification settings - Fork 56
/
avl_tree.c
127 lines (122 loc) · 2.42 KB
/
avl_tree.c
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data, height;
struct node *left;
struct node *right;
};
struct node *construct(int val)
{
struct node *n = (struct node *)malloc(sizeof(struct node));
n->data = val;
n->left = NULL;
n->right = NULL;
n->height = 1;
return n;
}
int getheight(struct node *n)
{
if (n == NULL)
{
return 0;
}
return n->height;
}
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
int getbalance(struct node *n)
{
if (n == NULL)
{
return 0;
}
return getheight(n->left) - getheight(n->right);
}
struct node *right(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 *left(struct node *x)
{
struct node *y = x->right;
struct node *t2 = y->left;
y->left = x;
x->right = t2;
x->height = max(getheight(x->right), getheight(x->left)) + 1;
y->height = max(getheight(y->right), getheight(y->left)) + 1;
return y;
}
struct node *insertion(struct node *n, int key)
{
if (n == NULL)
{
return construct(key);
}
if (key < n->data)
{
n->left = insertion(n->left, key);
}
else if (key > n->data)
{
n->right = insertion(n->right, key);
}
n->height = 1 + max(getheight(n->left), getheight(n->right));
int bf = getbalance(n);
// ll
if (bf > 1 && key < n->left->data)
{
return right(n);
}
// rr
if (bf < -1 && key > n->right->data)
{
return left(n);
}
// lr
if (bf > 1 && key > n->left->data)
{
n->left = left(n->left);
return right(n);
}
// rl
if (bf < -1 && key < n->right->data)
{
n->right = right(n->right);
return left(n);
}
return n;
}
void inorder(struct node *root)
{
if (root != NULL)
{
printf("%d ", root->data);
inorder(root->left);
inorder(root->right);
}
}
int main()
{
struct node *root = NULL;
root = insertion(root, 5);
root = insertion(root, 6);
root = insertion(root, 7);
root = insertion(root, 8);
root = insertion(root, 9);
printf("Inorder traversal: ");
inorder(root);
printf("\n%d", root->data);
return 0;
}