AC Code:
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int data,height;//data为结点数据域,height为高度
node *left,*right;//分别为左右孩子结点指针
};
node* creatnode(int x){//创建新结点
node *root=new node;
root->data=x;//把x赋给数据域
root->height=1;//高度初始化为1
root->left=root->right=NULL;//左右孩子指针初始化为NULL
return root;
}
int getheight(node *root){//获取高度
if(root==NULL) return 0;//要注意空结点的高度,防止段错误
return root->height;
}
void updataheight(node *root){//更新高度
root->height=max(getheight(root->left),getheight(root->right))+1;
//本结点高度等于左右子树高度的最大值加1
}
int balancefactor(node* root){//计算平衡因子
return getheight(root->left)-getheight(root->right);
}
void R(node* &root){//右旋
node* temp=root->left;
root->left=temp->right;
temp->right=root;
updataheight(root);
updataheight(temp);
root=temp;
}
void L(node* &root){//左旋
node* temp=root->right;
root->right=temp->left;
temp->left=root;
updataheight(root);//先更新旋转后位于下面的结点高度
updataheight(temp);//再更新旋转后位于上面的结点高度
root=temp;
}
void insertnode(node* &root,int x){//插入结点操作
if(root==NULL){//到达空结点,即插入位置
root=creatnode(x);
return;
}
if(x<root->data){//x小于当前结点数据域
insertnode(root->left,x);//应插入到左子树
updataheight(root);//更新高度
if(balancefactor(root)==2){
if(balancefactor(root->left)==1)//LL型
R(root);
else{
L(root->left);//LR型
R(root);
}
}
}
else{//x大于当前结点数据域
insertnode(root->right,x);//应插入到右子树
updataheight(root);//更新高度
if(balancefactor(root)==-2){
if(balancefactor(root->right)==-1)//RR型
L(root);
else{
R(root->right);//RL型
L(root);
}
}
}
}
int main(){
int n,x;
scanf("%d",&n);//输入结点总数
node* root=NULL;//创建根节点指针,初始化为NULL
for(int i=0;i<n;i++){
scanf("%d",&x);//边读入边插入
insertnode(root,x);
}
printf("%d",root->data);//输入根节点数据域
return 0;
}