-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram-3.cpp
More file actions
114 lines (86 loc) · 2.24 KB
/
program-3.cpp
File metadata and controls
114 lines (86 loc) · 2.24 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
/*
AVL Tree Implementation Based on Operations
*/
#include <iostream>
using namespace std;
class Node {
public:
int key, height;
Node *left, *right;
Node(int k) {
key = k;
height = 1;
left = right = NULL;
}
};
class AVL {
public:
int height(Node* n) {
return n ? n->height : 0;
}
int balance(Node* n) {
return n ? height(n->left) - height(n->right) : 0;
}
Node* rightRotate(Node* y) {
Node* x = y->left;
Node* 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;
}
Node* leftRotate(Node* x) {
Node* y = x->right;
Node* 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;
}
Node* insert(Node* node, int key) {
if (!node)
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
return node;
node->height = 1 + max(height(node->left), height(node->right));
int b = balance(node);
if (b > 1 && key < node->left->key)
return rightRotate(node);
if (b < -1 && key > node->right->key)
return leftRotate(node);
if (b > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (b < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void inorder(Node* root) {
if (root) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
};
int main() {
AVL tree;
Node* root = NULL;
int n, x;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
root = tree.insert(root, x);
}
tree.inorder(root);
return 0;
}