- #include<bits/stdc++.h>
-
- using namespace std;
- typedef struct node;
- typedef node * tree;
- struct node
- {
- int v;
- int heigh;
- tree L,R;
- };
- //获取以root为根结点的子树的当前height
- int getheigh(tree root)
- {
- if(root==NULL) return 0;
- return root->heigh;
- }
- //更新结点root的heigh
- void updataheigh(tree root)
- {
- //max(左孩子结点的height,有孩子结点的height)+1
- root->heigh=max(getheigh(root->L),getheigh(root->R))+1;
- }
- //计算平衡因子
- int getBalance(tree root)
- {
- //左-右
- return getheigh(root->L)-getheigh(root->R);
- }
- //左旋 注意原理 对于RR是root的右孩子的平衡因子是-1
- void L(tree &root)
- {
- tree temp;
- temp=root->R;
- root->R=temp->L;
- temp->L=root;
- updataheigh(root);
- updataheigh(temp);
- root=temp;
- }
- void R(tree &root)
- {
- tree temp;
- temp=root->L;
- root->L=temp->R;
- temp->R=root;
- updataheigh(root);
- updataheigh(temp);
- root=temp;
- }
- void insertt(tree &root,int v)
- {
- if(root==NULL){//当结点是空的时候 就是插入的时候
- root=new node;
- root->v=v;
- root->heigh=1;
- root->L=root->R=NULL;
- return;
- }
- if(v<root->v){
- insertt(root->L,v);
- updataheigh(root);//注意更新树高
- if(getBalance(root)==2){
- if(getBalance(root->L)==1){
- R(root);
- }
- else if(getBalance(root->L)==-1){
- L(root->L);
- R(root);
- }
- }
- }
- else{
- insertt(root->R,v);
- updataheigh(root);
- if(getBalance(root)==-2){
- if(getBalance(root->R)==-1){
- L(root);
- }
- else if(getBalance(root->R)==1){
- R(root->R);
- L(root);
- }
- }
- }
- }
- int main()
- {
- int n;
- scanf("%d",&n);
- int x;
- tree root;
- root=NULL;
- for(int i=0;i<n;i++){
- scanf("%d",&x);
- insertt(root,x);
- }
- printf("%d\n",root->v);
- return 0;
- }