也就主要按照排序二叉树的建立并以LL,RR,LR,RL四种方式的旋转来调整得到,AVL(二叉平衡树)。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<queue>
#include<map>
#include<stack>
#define L1 long long
#define L2 int
#define inf 0x3f3f3f3f
using namespace std;
const int m1=1001000;
const int m2=1010;
struct node
{
int d,h;
node *l,*r;
};
int dp(node *rt){
if(!rt)
return -1;
else
return rt->h;
}
node *RR(node *(&rt) ){
node *p;
p=rt->l;
rt->l=p->r;
p->r=rt;
rt->h=max(dp(rt->l),dp(rt->r))+1;
p->h=max(dp(p->l),rt->h)+1;
return p;
}
node *LL(node *(&rt) ){
node *p;
p=rt->r;
rt->r=p->l;
p->l=rt;
rt->h=max(dp(rt->l),dp(rt->r))+1;
p->h=max(dp(p->r),rt->h)+1;
return p;
}
node *RL(node *(&rt) ){
rt->r=LL(rt->r);
return RR(rt);
}
node *LR(node *(&rt) ){
rt->l=RR(rt->l);
return LL(rt);
}
node *bu(node *rt,int k){
if(rt==NULL)
{
rt=new node;
rt->d=k;
rt->h=0;
rt->l=rt->r=NULL;
}
else
{
if(rt->d>k){
rt->l=bu(rt->l,k);
if(dp(rt->l)-dp(rt->r)>1 ){
if(rt->l->d>k ){
rt=RR(rt);
}
else{
rt=RL(rt);
}
}
}
else
{
rt->r=bu(rt->r,k);
if(dp(rt->r)-dp(rt->l)>1){
if(rt->r->d<k){
rt=LL(rt);
}
else{
rt=LR(rt);
}
}
}
}
rt->h=max(dp(rt->l),dp(rt->r))+1;
return rt;
}
int main()
{
int n,m,i,j,k;
while(~scanf("%d",&n)){
node *rt;
rt=new node;
rt=NULL;
for(i=0;i<n;i++){
scanf("%d",&k);
rt=bu(rt,k);
}
printf("%d\n",rt->d);
}
return 0;
}