-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVL.cpp
More file actions
123 lines (104 loc) · 2.18 KB
/
AVL.cpp
File metadata and controls
123 lines (104 loc) · 2.18 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
111
112
113
114
115
116
117
118
119
120
121
122
123
// student no: A00030840
#include "AVL.h"
// get the height of the tree
int AVL::getHeight(node* node) {
if (node == NULL)
return 0;
else {
int leftDepth = getHeight(node->left);
int rightDepth = getHeight(node->right);
if (leftDepth > rightDepth) {
return(leftDepth + 1);
}
else {
return(rightDepth + 1);
}
}
}
// return balance factor of the tree
int AVL::getBalanceFactor(struct node* N)
{
if (N == NULL)
return 0;
return getHeight(N->left) - getHeight(N->right);
}
struct node* AVL::leftRotation(struct node* n) {
struct node* p;
struct node* tp;
p = n;
tp = p->left;
p->left = tp->right;
tp->right = p;
return tp;
}
struct node* AVL::rightRotation(struct node* n) {
struct node* p;
struct node* tp;
p = n;
tp = p->right;
p->right = tp->left;
tp->left = p;
return tp;
}
struct node* AVL::rightLeftRotation(struct node* n) {
struct node* p;
struct node* tp;
struct node* tp2;
p = n;
tp = p->right;
tp2 = p->right->left;
p->right = tp2->left;
tp->left = tp2->right;
tp2->left = p;
tp2->right = tp;
return tp2;
}
struct node* AVL::leftRightRotation(struct node* n) {
struct node* p;
struct node* tp;
struct node* tp2;
p = n;
tp = p->left;
tp2 = p->left->right;
p->left = tp2->right;
tp->right = tp2->left;
tp2->right = p;
tp2->left = tp;
return tp2;
}
// return node
struct node* AVL::insert(struct node* r, int data) {
if (r == NULL) {
struct node* n;
n = new struct node;
n->data = data;
r = n;
r->left = r->right = NULL;
r->height = 1;
return r;
}
else {
if (data < r->data)
r->left = insert(r->left, data);
else
r->right = insert(r->right, data);
}
r->height = getHeight(r);
// perform left rotation
if (getBalanceFactor(r) == 2 && getBalanceFactor(r->left) == 1) {
r = leftRotation(r);
}
// perform right rotation
else if (getBalanceFactor(r) == -2 && getBalanceFactor(r->right) == -1) {
r = rightRotation(r);
}
// perform right left rotation
else if (getBalanceFactor(r) == -2 && getBalanceFactor(r->right) == 1) {
r = rightLeftRotation(r);
}
// perform left right rotation
else if (getBalanceFactor(r) == 2 && getBalanceFactor(r->left) == -1) {
r = leftRightRotation(r);
}
return r;
}