-
Notifications
You must be signed in to change notification settings - Fork 2
/
A1066.cpp
90 lines (81 loc) · 1.68 KB
/
A1066.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
#include <cstdio>
#include <algorithm>
using namespace std;
int N;
struct Node{
int data, height;
Node *lchild, *rchild;
Node(int d) : data(d), height(1), lchild(NULL), 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 getBalanceFactor(Node *root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
void R(Node *&root){
Node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void L(Node *&root){
Node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(Node *&root, int data){
if(root == NULL){
root = new Node(data);
}else if(data < root->data){
insert(root->lchild, data);
updateHeight(root);
if(getBalanceFactor(root) == 2){
if(getBalanceFactor(root->lchild) == 1){
R(root);
}else if(getBalanceFactor(root->lchild) == -1){
L(root->lchild);
R(root);
}
}
}else{
insert(root->rchild, data);
updateHeight(root);
if(getBalanceFactor(root) == -2){
if(getBalanceFactor(root->rchild) == -1){
L(root);
}else if(getBalanceFactor(root->rchild) == 1){
R(root->rchild);
L(root);
}
}
}
}
void free(Node *root){
if(root == NULL) return;
free(root->lchild);
free(root->rchild);
delete root;
root = NULL;
}
int main(){
scanf("%d", &N);
Node *root = NULL;
for(int i = 0; i < N; ++i){
int data;
scanf("%d", &data);
insert(root, data);
}
printf("%d", root->data);
free(root);
return 0;
}