#include <iostream>
using namespace std;
int max(int a,int b)
{
return a>b?a:b;
}
class AvlTree
{
public:
struct node
{
int value;
node *left,*right;
int height;
node(int v):value(v),left(NULL),right(NULL),height(1){};
};
node *root;
AvlTree(){root=NULL;}
inline int GetHeight(node *r)
{
if(r==NULL) return 0;
else return r->height;
}
inline bool IsBalance(node *r)
{
return abs(GetHeight(r->left)-GetHeight(r->right))<2;
}
node* Retate_L(node *r)
{
node *r1;
r1=r->left;
r->left=r1->right;
r1->right=r;
r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
r1->height=max(GetHeight(r1->left),GetHeight(r1->right))+1;
return r1;
}
node* Retate_R(node *r)
{
node *r1;
r1=r->right;
r->right=r1->left;
r1->left=r;
r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
r1->height=max(GetHeight(r1->left),GetHeight(r1->right))+1;
return r1;
}
node* Retate_LR(node *r)
{
r->right=Retate_L(r->right);
return Retate_R(r);
}
node* Retate_RL(node *r)
{
r->left=Retate_R(r->left);
return Retate_L(r);
}
node* insert(node *r,int v)
{
if(r==NULL)
{
r=new node(v);
return r;
}
if(v<r->value)
{
r->left=insert(r->left,v);
r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
if(!IsBalance(r))
{
if(v<r->left->value) r=Retate_L(r);
else r=Retate_RL(r);
}
}
else
{
r->right=insert(r->right,v);
r->height=max(GetHeight(r->left),GetHeight(r->right))+1;
if(!IsBalance(r))
{
if(v>=r->right->value) r=Retate_R(r);
else r=Retate_LR(r);
}
}
return r;
}
void insert(int v)
{
root=insert(root,v);
}
};
class CA
{
public:
AvlTree at;
void run();
};
void CA::run()
{
int n,t;
scanf("%d",&n);
while(n-->0)
{
scanf("%d",&t);
at.insert(t);
}
printf("%d\n",at.root->value);
}
int main()
{
// freopen("test.in","r",stdin);
CA *a=new CA;
a->run();
return 0;
}
1066. Root of AVL Tree (25)
最新推荐文章于 2020-08-24 16:57:04 发布