平衡二叉查找树的相关概念与旋转操作参考:点击打开链接
AC代码:
#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<list>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
using namespace std;
struct node
{
int data;
struct node* l=NULL;
struct node* r=NULL;
int h=0;
};
int heigt(node* k3)
{
if(k3!=NULL)
return k3->h;
else
return -1;
}
void SLL(node* &k2)
{
node* k1;
k1=k2->l;
k2->l=k1->r;
k1->r=k2;
k2->h=max(heigt(k2->l),heigt(k2->r))+1;
k1->h=max(heigt(k1->l),k2->h)+1;
k2=k1;
}
void SRR(node* &k2)
{
node* k1;
k1=k2->r;
k2->r=k1->l;
k1->l=k2;
k2->h=max(heigt(k2->l),heigt(k2->r))+1;
k1->h=max(heigt(k1->r),k2->h)+1;
k2=k1;
}
void DLR(node* &k3)
{
SRR(k3->l);
SLL(k3);
}
void DRL(node* &k3)
{
SLL(k3->r);
SRR(k3);
}
void Insert(node* &root,int x)
{
if(root==NULL)
{
root=new node;
root->data=x;
return ;
}
if(root->data>x)
{
Insert(root->l,x);
if(2==heigt(root->l)-heigt(root->r))
{
//cout<<1<<endl;
if(x<root->l->data)
{
SLL(root);
}
else
{
DLR(root);
}
}
}
else if(root->data<x)
{
Insert(root->r,x);
if(2==heigt(root->r)-heigt(root->l))
{
if(x>root->r->data)
{
SRR(root);
}
else
{
DRL(root);
}
}
}
root->h=max(heigt(root->l),heigt(root->r))+1;
}
int main()
{
int n;
scanf("%d",&n);
node* root=NULL;
for(int i=0;i<n;i++)
{
int d;
scanf("%d",&d);
Insert(root,d);
//cout<<root->data<<endl;
}
printf("%d",root->data);
}