-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVL_Tree.cpp
146 lines (115 loc) · 2.64 KB
/
AVL_Tree.cpp
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
AVL Tree
*/
#include<iostream>
using namespace std;
class AVLTreeNode {
int data;
AVLTreeNode* left;
AVLTreeNode* right;
int height;
friend class AVLTree;
};
class AVLTree {
private:
AVLTreeNode* root;
int height(AVLTreeNode* node) {
if (node == NULL)
return -1;
return node->height;
}
int max(int a, int b) {
if (a > b) {
return a;
}
else {
return b;
}
}
AVLTreeNode* rightRotate(AVLTreeNode* y) {
AVLTreeNode* x = y->left;
AVLTreeNode* T = x->right;
x->right = y;
y->left = T;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
AVLTreeNode* leftRotate(AVLTreeNode* x) {
AVLTreeNode* y = x->right;
AVLTreeNode* T = y->left;
y->left = x;
x->right = T;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(AVLTreeNode* node) {
if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}
AVLTreeNode* insert(AVLTreeNode* node, int val) {
if (node == NULL) {
AVLTreeNode* newNode = new AVLTreeNode;
newNode->data = val;
newNode->left = newNode->right = NULL;
newNode->height = 0;
return newNode;
}
if (val < node->data)
node->left = insert(node->left, val);
else if (val > node->data)
node->right = insert(node->right, val);
else
return node; // Duplicate values not allowed
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
// Left Heavy
if (balance > 1 && val < node->left->data)
return rightRotate(node);
// Right Heavy
if (balance < -1 && val > node->right->data)
return leftRotate(node);
// Left Right Heavy
if (balance > 1 && val > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Heavy
if (balance < -1 && val < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void inOrder(AVLTreeNode* node) {
if (node != NULL) {
inOrder(node->left);
cout << node->data << " ";
inOrder(node->right);
}
}
public:
AVLTree() {
root = NULL;
}
void insert(int val) {
root = insert(root, val);
}
void inOrder() {
inOrder(root);
cout << endl;
}
};
int main() {
AVLTree avl;
avl.insert(5);
avl.insert(7);
avl.insert(4);
avl.insert(3);
cout << "In-Order Traversal of AVL Tree: ";
avl.inOrder();
system("pause>nul");
return 0;
}