#include<bits/stdc++.h>
using namespace std;
struct node{
int val;
node* left;
node* right;
};
node* rotater(node* root){
node* t=root->left;
root->left=t->right;
t->right=root;
return t;
}
node* rotatel(node* root){
node* t=root->right;
root->right=t->left;
t->left=root;
return t;
}
node* rotatelr(node* root){
root->left=rotatel(root->left);
return rotater(root);
}
node* rotaterl(node* root){
root->right=rotater(root->right);
return rotatel(root);
}
int geth(node* root){
if(root==NULL) return 0;
return max(geth(root->left),geth(root->right))+1;
}
node* insert(node* root,int u){
if(root==NULL){
root=new node();
root->val=u;
root->left=NULL;
root->right=NULL;
}
else if(u<root->val){
root->left=insert(root->left,u);
if(geth(root->left)-geth(root->right)==2){
if(u<root->left->val) root=rotater(root);
else root=rotatelr(root);
}
}
else{
root->right=insert(root->right,u);
if(geth(root->right)-geth(root->left)==2){
if(u>root->right->val) root=rotatel(root);
else root=rotaterl(root);
}
}
return root;
}
int main(){
int n;
scanf("%d",&n);
node* root=NULL;
for(int i=0;i<n;i++){
int t;scanf("%d",&t);
root=insert(root,t);
}
printf("%d\n",root->val);
return 0;
}
平衡树(旋转)
最新推荐文章于 2022-10-09 18:18:21 发布