-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1066_Root_of_AVL_Tree.cpp
94 lines (83 loc) · 1.94 KB
/
1066_Root_of_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
#include <bits/stdc++.h>
using namespace std;
typedef struct Node* node;
struct Node {
int val;
node left;
node right;
Node(int v) {
val = v;
left = NULL;
right = NULL;
}
};
node rightRotate(node root) {
node temp = root->left;
root->left = temp->right;
temp->right = root;
return temp;
}
node leftRotate(node root) {
node temp = root->right;
root->right = temp->left;
temp->left = root;
return temp;
}
node rightLeft(node root) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
node leftRight(node root) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
int findHeight(node root) {
if (root == NULL) return 0;
int l = findHeight(root->left);
int r = findHeight(root->right);
return max(l, r) + 1;
}
void insertNode(node& root, int val) {
if (root == NULL) {
root = new Node(val);
} else if (root->val > val) {
insertNode(root->left, val);
int l = findHeight(root->left);
int r = findHeight(root->right);
if (abs(r - l) > 1) {
if (root->left->val > val) {
root = rightRotate(root);
} else {
root = leftRight(root);
}
}
} else {
insertNode(root->right, val);
int l = findHeight(root->left);
int r = findHeight(root->right);
if (abs(r - l) > 1) {
if (root->right->val < val) {
root = leftRotate(root);
} else {
root = rightLeft(root);
}
}
}
}
void preTraveser(node root) {
if (root == NULL) return;
cout << root->val << " ";
preTraveser(root->left);
preTraveser(root->right);
}
int main() {
int n, t;
cin >> n;
node root = NULL;
for (int i = 0; i < n; ++i) {
cin >> t;
insertNode(root, t);
}
cout << root->val << endl;
return 0;
}