AVL左旋和右旋操作:
- LL时,需要进行右旋
- RR时,需要进行左旋
- LR时,先左旋再右旋
- RL时,先右旋再左旋
所以判断当前状态后,只需左右旋两个基本操作。这两个基本操作,需要参考一个比较的不平衡树来写代码。
#include<bits/stdc++.h>
using namespace std;
struct node{
node *l,*r;
int v;
};
node *rotateLeft(node *rt){
node *temp = rt->r;
rt->r = temp->l;
temp->l = rt;
return temp;
}
node *rotateRight(){
node *temp = rt->l;
rt->l = temp->r;
temp->r = rt;
return temp;
}
node *RR(node *rt){ //rotate left
return rotateLeft(rt);
}
node *LL(node *rt){ //rotate right
return rotateRight(rt);
}
node *RL(node *rt){
rt->r = rotateRight(rt->r); //rotate right
return rotateLeft(rt); //rotate left
}
node *LR(node *rt){
rt->l = rotateLeft(rt->l); //rotate left
return rotateRight(rt); //rotate right
}
int getHeight(node *rt){
if(rt==NULL)return 0;
return max(getHeight(rt->l),getHeight(rt->r))+1;
}
node *insert(node *rt,int v){
if(rt == NULL){
rt = new node();
rt->l=NULL;
rt->r=NULL;
rt->v=v;
return rt; //tmp
}
if(rt->v > v){
rt->l = insert(rt->l,v);
if(abs(getHeight(rt->r)-getHeight(rt->l))==2){
if(rt->l->v > v){
rt=LL(rt);
}else{
rt=LR(rt);
}
}
}else{
rt->r = insert(rt->r,v);
if(abs(getHeight(rt->r)-getHeight(rt->l))==2){
if(rt->r->v > v){
rt=RL(rt);
}else{
rt=RR(rt);
}
}
}
return rt;
}
int main(){
int n,tmp;
scanf("%d",&n);
node *tree=NULL;//init
for(int i=0;i<n;++i){
scanf("%d",&tmp);
tree=insert(tree,tmp);
}
printf("%d",tree->v);
return 0;
}