AVL平衡二叉树 实现 查询时间复杂度 O(logn)
LL 左旋 root 2 root->lchild=1
LR 左旋后右旋 root 2 root->lchild=-1
RR 右旋 root=-2 root->rchild=-1
RL 右旋后左旋 root=-2 root->rchild=1
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
int data;
node *right ,*left;
int height;
};
node * newnode(int v)
{
node * nd=new node;
nd->data=v;
nd->left=NULL;nd->right=NULL;
nd->height=1;
}
int getheight(node * nd)
{
if(nd==NULL)return 0;
return nd->height;
}
int getbalancefactor(node *nd)
{
//if(nd==NULL) return 0;
//return nd->left->height-nd->right->height;
return getheight(nd->left)-getheight(nd->right);
}
void updateheight(node *nd)
{
//nd->height=max(nd->left->height,nd->right->height)+1;
nd->height=max(getheight(nd->left),getheight(nd->right))+1;
}
void l(node * &root)//左旋
{
node *temp=root->left;
root->right=temp->left;
temp->left=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void r(node * &root)//右旋
{
node*temp=root->right;
root->left=temp->right;
temp->right=root;
updateheight(root);
updateheight(temp);
root=temp;
}
void insert (node * &root ,int v)
{
if(root==NULL)
{
newnode(v);
return;
}
if(v<root->data)
{
insert(root->left,v);
updateheight(root);
if(getbalancefactor(root)==2)
{
if(getbalancefactor(root->left)==1)
{
r(root);
}
else
{
r(root->left);
l(root);
}
}
}
else
{
insert(root->right,v);
updateheight(root);
if(getbalancefactor(root)==-2)
{
if(getbalancefactor(root->right)==-1)
{
l(root);
}
else
{
l(root->right);
r(root);
}
}
}
}
const int maxn=21;
int main()
{
int n,a;
scanf("%d",&n);
node *root=NULL;
for(int i=0;i<n;i++)
{
scanf("%d",&a);
insert(root,a);
}
printf("%d",root->data);
return 0;
}