struct node
{
int data,height;
node *lchild,*rchild;
};
//新建结点
node *newnode(int x)
{
node *root=new node;
root->data=x;
root->lchild=root->rchild=NULL;
root->height=1;
return root;
}
//获取root所在字树的当前高度
int getheight(node *root)
{
if(root==NULL)
return 0;
return root->height;
}
//计算平衡因子
int getbla(node *root)
{
return getheight(root->lchild)-getheight(root->rchild);
}
//更新结点高度
void upheight(node *root)
{//root所在子树的高度等于其左子树和右子树的高度较大的+1
root->height=max(getheight(root->lchild),getheight(root->rchild))+1;
}
//左旋
void left(node *&root)
{
node *temp=root->rchild;
root->rchild=temp->lchild; //左旋根右转
temp->lchild=root;
upheight(root);
upheight(temp);
root=temp;
}
void right(node *&root)
{
node *temp=root->lchild;
root->lchild=temp->rchild; //左旋根右转
temp->rchild=root;
upheight(root);
upheight(temp);
root=temp;
}
//难点 插入权值为v的 且要考虑平衡因子
void insert(node* &root,int v)
{
if(root==NULL)
{
root=newnode(v);
return;
}
if(v<root->data)//比根小 插左边
{
insert(root->lchild,v);
upheight(root);//更新树高
if(getheight(root)==2)
{
if(getbla(root->lchild)==1)//LL型
right(root);
else if(getbla(root->lchild)==-1)//LR型
{
left(root->lchild);
right(root);
}
}
}
else//大 插右边
{
insert(root->rchild,v);
upheight(root);
if(getheight(root)==-2)
{
if(getbla(root->rchild)==-1)//LL型
left(root);
else if(getbla(root->rchild)==1)//LR型
{
right(root->rchild);
left(root);
}
}
}
}
//建树
node *creat(int x[],int n)
{
node *root=NULL;
for(int i=0;i<n;i++)
insert(root,x[i]);
return root;
}