//就本题而言其实不更新树高也可以
#include <iostream>
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
int height;
};
int Max(int a,int b){
return a>b? a:b;
}
int GetHeight(node* root){
//递归求树高
if(!root) return 0;
else{
return Max(GetHeight(root->lchild),GetHeight(root->rchild))+1;
}
}
//LL、RR、LR、RL:改变子树位置,更新树高
node* singleLeftRotation(node* A){
node* B=A->lchild;
A->lchild=B->rchild;
B->rchild=A;
//更新树高:使用当前改变后的子树最易
A->height=Max(GetHeight(A->lchild),GetHeight(A->rchild))+1;
B->height=Max(A->height,GetHeight(B->lchild))+1;
return B;
}
node* singleRightRotation(node* A){
node* B=A->rchild;
A->rchild=B->lchild;
B->lchild=A;
//更新树高:使用当前改变后的子树最易
A->height=Max(GetHeight(A->lchild),GetHeight(A->rchild))+1;
B->height=Max(A->height,GetHeight(B->rchild))+1;
return B;
}
node* doubleLeftRightRotation(node* A){
//不能新建一个变量B对B修改,而要直接修改A->lchild的值
A->lchild=singleRightRotation(A->lchild);
return singleLeftRotation(A);
}
node* doubleRightLeftRotation(node* A){
//不能新建一个变量B对B修改,而要直接修改A->rchild的值
A->rchild=singleLeftRotation(A->rchild);
return singleRightRotation(A);
}
node* Insert(node* root,int x){
if(!root){
node* t=new node;
t->data=x;
t->height=0;
t->lchild=t->rchild=NULL;
root=t;
}else{
if(x<root->data){
root->lchild=Insert(root->lchild,x);
if(GetHeight(root->lchild)-GetHeight(root->rchild)==2){
//插在左子树的左or右子树上,应比较左子树的data
if(x < root->lchild->data) root=singleLeftRotation(root);
else root=doubleLeftRightRotation(root);
}
}
else if(x>root->data){
root->rchild=Insert(root->rchild,x);
if(GetHeight(root->lchild)-GetHeight(root->rchild)==-2){
//插在右子树的左or右子树上,应比较右子树的data
if(x > root->rchild->data) root=singleRightRotation(root);
else root=doubleRightLeftRotation(root);
}
}
}
root->height=Max(GetHeight(root->lchild),GetHeight(root->rchild))+1;
return root;
}
int main(){
int N,tmp;
cin>>N;
node* root=NULL;
for(int i=0;i<N;i++){
cin>>tmp;
root=Insert(root,tmp);
}
cout<<root->data;
return 0;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交