-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1066.cpp
79 lines (78 loc) · 1.43 KB
/
1066.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
#include <bits/stdc++.h>
using namespace std;
struct node{
int data, height;
node *lchild, *rchild;
node(int x){
data = x;
height = 1;
lchild = rchild = NULL;
}
};
int getHeight(node* root){
if(root == NULL) return 0;
else return root->height;
}
void updateHeight(node* root){
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
int getBalance(node* root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
void L(node* &root){
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node* &root){
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node* &root, int x){
if(root == NULL){
root = new node(x);
return;
}
if(x < root->data){
insert(root->lchild, x);
updateHeight(root);
if(getBalance(root) == 2){
if(getBalance(root->lchild) == 1){
R(root);
}else if(getBalance(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}else{
insert(root->rchild, x);
updateHeight(root);
if(getBalance(root) == -2){
if(getBalance(root->rchild) == -1){
L(root);
}else if(getBalance(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}
int main(){
node* root = NULL;
int n;
cin>>n;
while(n--){
int x;
cin>>x;
insert(root, x);
}
cout<<root->data;
return 0;
}