手搓AVL树的插入。
回去复习了一年前学的数据结构课本的15章,AVL树插入的平衡处理,有四种情况:LL旋转、LR选中、RR旋转、RL旋转
#include<bits/stdc++.h>
using namespace std;
struct node{
int val;
node *l,*r;
node(int x):val(x),l(NULL),r(NULL){}
};
int height(node* root){
if(root==NULL) return 0;
return max(height(root->l),height(root->r))+1;
}
node* LL(node* root){
node* temp=root->l;
root->l=temp->r;
temp->r=root;
return temp;
}
node* RR(node* root){
node* temp=root->r;
root->r=temp->l;
temp->l=root;
return temp;
}
node* LR(node* root){
root->l=RR(root->l);
return LL(root);
}
node* RL(node* root){
root->r=LL(root->r);
return RR(root);
}
node* insert(node* root,int val){
if(root==NULL)
root=new node(val);
else if(val<root->val){
root->l=insert(root->l,val);
if(height(root->l)-height(root->r)>=2){
// 平衡操作
if(val<root->l->val) root=LL(root);
else root=LR(root);
}
}else{
root->r=insert(root->r,val);
if(height(root->r)-height(root->l)>=2){
// 平衡操作
if(val>=root->r->val) root=RR(root);
else root=RL(root);
}
}
return root;
}
int main(){
int n,val;
node* root=NULL;
scanf("%d",&n);
while(n--){
scanf("%d",&val);
root=insert(root,val);
}
printf("%d",root->val);
return 0;
}