/* ***********************************************
Author :xryz
Email :523689985@qq.com
Created Time :4-8 22:26:56
File Name :RootofAVLTree.cpp
************************************************ */
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef struct avltreenode *avltree;
typedef struct avltreenode{
int data;
avltree left;
avltree right;
int height;
};
int getheight(avltree a)
{
if(a==NULL) return -1;
return a->height;
}
//a必须有一个左子结点b
//a与b做左单旋,更新a与b高度,返回新的根结点b
avltree singleleftrotation(avltree a)
{
avltree b=a->left;
a->left=b->right;
b->right=a;
a->height=max(getheight(a->left),getheight(a->right))+1;
b->height=max(getheight(b->left),a->height)+1;
return b;
}
//右单旋转
avltree singlerightrotation(avltree a)
{
avltree b=a->right;
a->right=b->left;
b->left=a;
a->height=max(getheight(a->left),getheight(a->right))+1;
b->height=max(getheight(b->right),a->height)+1;
return b;
}
//a必须有一个左子结点b,且b必须有一个右子结点c
//a,b,c,做两次单旋,返回新的根结点c
avltree doubleleftrightrotation(avltree a)
{
a->left=singlerightrotation(a->left);
return singleleftrotation(a);
}
avltree doublerightleftrotation(avltree a)
{
a->right=singleleftrotation(a->right);
return singlerightrotation(a);
}
avltree avl_insertion(int x,avltree t)
{
/*将X插入avl树T中,并返回调整后的avl树*/
if(!t)/*插入空树,则新建包含一个结点的树*/
{
t=(avltree)malloc(sizeof(struct avltreenode));
t->data=x;
t->height=0;
t->left=t->right=NULL;
}/*插入空树结束*/
else if(x<t->data)
{
t->left=avl_insertion(x,t->left);
if(getheight(t->left)-getheight(t->right)==2)
{
/*需要左旋*/
if(x<t->left->data)
t=singleleftrotation(t);//左单旋 singleleftrotation
else
t=doubleleftrightrotation(t);//左右双旋
}
}
else if(x>t->data)
{
t->right=avl_insertion(x,t->right);
if(getheight(t->left)-getheight(t->right)==-2)
{
/*需要右旋*/
if(x>t->right->data)
t=singlerightrotation(t);//右单旋
else
t=doublerightleftrotation(t);//右左双旋
}
}
//x=data,无须插入
t->height=max(getheight(t->left),getheight(t->right))+1;
return t;
}
int main()
{
int n,i,num;
avltree root;
while(~scanf("%d",&n))
{
for(i=0;i<n;i++)
{
scanf("%d",&num);
root=avl_insertion(num,root);
}
printf("%d\n",root->data);
free(root);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/