#include <iostream>
using namespace std;
struct node{
int val;
struct node*left,*right;
};
node* rotateleft(node* root){
node*t=root->right;
root->right = t->left;
t->left=root;
return t;
}
node* rotateright(node* root){
node*t=root->left;
root->left=t->right;
t->right=root;
return t;
}
node*rotateLeftRight(node *root){
root->left=rotateleft(root->left);
return rotateright(root);
}
node*rotateRightLeft(node *root){
root->right=rotateright(root->right);
return rotateleft(root);
}
int getHeight(node *root) {
if(root == NULL) return 0;
return max(getHeight(root->left), getHeight(root->right)) + 1;
}
node* insert(node *root, int val){
if(root==NULL){
root=new node();
root->val=val;
}else if(val>root->val){
root->right=insert(root->right,val);
if(getHeight(root->left)-getHeight(root->right)==-2)
root=val>root->right->val?rotateleft(root):rotateRightLeft(root);
}else{
root->left=insert(root->left,val);
if(getHeight(root->left)-getHeight(root->right)==2)
root=val>root->left->val?rotateLeftRight(root):rotateright(root);
}
return root;
}
int main() {
int n,val;
cin>>n;
node *root=NULL;
for(int i=0;i<n;i++){
scanf("%d",&val);
root=insert(root,val);
}
cout<<root->val;
system("pause");
return 0;
}
PAT 1066 Root of AVL Tree (25 分)
最新推荐文章于 2024-11-12 15:39:48 发布