forked from akkupy/codeDump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAVL_tree.cpp
129 lines (100 loc) · 2.96 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
#include <iostream>
#include <algorithm>
class AVLTree {
private:
struct Node {
int key;
Node* left;
Node* right;
int height;
Node(int k) : key(k), left(nullptr), right(nullptr), height(1) {}
};
Node* root;
int getHeight(Node* node) {
if (node == nullptr) return 0;
return node->height;
}
int getBalanceFactor(Node* node) {
if (node == nullptr) return 0;
return getHeight(node->left) - getHeight(node->right);
}
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = 1 + std::max(getHeight(y->left), getHeight(y->right));
x->height = 1 + std::max(getHeight(x->left), getHeight(x->right));
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = 1 + std::max(getHeight(x->left), getHeight(x->right));
y->height = 1 + std::max(getHeight(y->left), getHeight(y->right));
return y;
}
Node* insert(Node* node, int key) {
if (node == nullptr) return new Node(key);
if (key < node->key) {
node->left = insert(node->left, key);
} else if (key > node->key) {
node->right = insert(node->right, key);
} else {
// Duplicate keys are not allowed
return node;
}
node->height = 1 + std::max(getHeight(node->left), getHeight(node->right));
int balance = getBalanceFactor(node);
// Left-Left case
if (balance > 1 && key < node->left->key) {
return rotateRight(node);
}
// Right-Right case
if (balance < -1 && key > node->right->key) {
return rotateLeft(node);
}
// Left-Right case
if (balance > 1 && key > node->left->key) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}
// Right-Left case
if (balance < -1 && key < node->right->key) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}
return node;
}
void inorder(Node* node) {
if (node == nullptr) return;
inorder(node->left);
std::cout << node->key << " ";
inorder(node->right);
}
public:
AVLTree() : root(nullptr) {}
void insert(int key) {
root = insert(root, key);
}
void printInorder() {
inorder(root);
std::cout << std::endl;
}
};
int main() {
AVLTree avl;
int n, key;
std::cout << "Enter the number of elements to insert: ";
std::cin >> n;
std::cout << "Enter the elements to insert, one by one:" << std::endl;
for (int i = 0; i < n; ++i) {
std::cin >> key;
avl.insert(key);
}
std::cout << "Inorder traversal of AVL tree: ";
avl.printInorder();
return 0;
}