#include <iostream>
#include <cstdio>
using namespace std;
struct node {
int key;
node *left, *right;
int h;
};
inline void update(node *t) {
int lh = t->left ? t->left->h : 0;
int rh = t->right ? t->right->h : 0;
t->h = (lh > rh ? lh : rh) + 1;
}
void insert(node * &t, int d) {
if(t) {
insert(d > t->key ? t->right : t->left, d);
int lh = t->left ? t->left->h : 0;
int rh = t->right ? t->right->h : 0;
if(lh - rh > 1) {
int llh = t->left->left ? t->left->left->h : 0;
int lrh = t->left->right ? t->left->right->h : 0;
if(llh > lrh) {
node *nt = t->left;
t->left = nt->right;
nt->right = t;
t = nt;
update(t->right);
}
else {
node *nt = t->left->right;
node *tl = t->left;
tl->right = nt->left;
t->left = nt->right;
nt->left = tl;
nt->right = t;
t = nt;
update(t->left);
update(t->right);
}
}
else if(lh - rh < -1) {
int rlh = t->right->left ? t->right->left->h : 0;
int rrh = t->right->right ? t->right->right->h : 0;
if(rrh > rlh) {
node *nt = t->right;
t->right = nt->left;
nt->left = t;
t = nt;
update(t->left);
}
else {
node *nt = t->right->left;
node *tr = t->right;
tr->left = nt->right;
t->right = nt->left;
nt->right = tr;
nt->left = t;
t = nt;
update(t->left);
update(t->right);
}
}
update(t);
}
else {
t = new node;
t->key = d;
t->left = t->right = 0;
t->h = 1;
}
}
int main(int argc, char **argv) {
int n;
cin >> n;
node *t = 0;
for(int i = 0; i < n; i ++) {
int d;
scanf("%d", &d);
insert(t, d);
}
printf("%d\n", t->key);
return 0;
}
1066. Root of AVL Tree (25)
最新推荐文章于 2020-08-24 16:57:04 发布