typedef struct bitnode//存储结构
{
int data;
int d;
struct bitnode *lchild, *rchild;
}* bitree;
int deep(bitree &t)//求结点的高度,左右子树相减即为平衡因子
{
if(!t)
return -1;
return t->d;
}
x的lchild连上a的rchild,a的rchild连上x,完成旋转。
bitree LL(bitree &t) //单旋转
{
bitree q;
q = t->lchild;
t->lchild = q->rchild;
q->rchild = t;
q->d = max(deep(q->lchild), deep(q->rchild))+1;
t->d = max(deep(t->lchild), deep(t->rchild))+1;//旋转之后更新结点的高度
return q;
}
x的rchild连上a的lchild,a的lchild连上x,完成旋转。
bitree RR(bitree &t)//单旋转
{
bitree q;
q = t->rchild;
t->rchild = q->lchild;
q->lchild = t;
q->d = max(deep(q->lchild), deep(q->rchild))+1;
t->d = max(deep(t->lchild), deep(t->rchild))+1;
return q;
}
旋转分两步:1.以a为根结点的RR旋转 2.以x为根结点的LL旋转 。
bitree LR(bitree &t)
{
t->lchild = RR(t->lchild);
return LL(t);
}
旋转分两步:1.以a为根结点的LL旋转 2.以x为根结点的RR旋转 。
bitree RL(bitree &t)
{
t->rchild = LL(t->rchild);
return RR(t);
}
bitree Insert(bitree &t, int x) //构造平衡二叉树
{
if(!t)
{
t = new bitnode;
t->lchild = NULL;
t->rchild = NULL;
t->data = x;
t->d = 0;
}
else if(x<t->data)
{
t->lchild = Insert(t->lchild, x);
if(deep(t->lchild)-deep(t->rchild)>1)
{
if(x<t->lchild->data)
t = LL(t);
else
t = LR(t);
}
}
else if(x>t->data)
{
t->rchild = Insert(t->rchild, x);
if(deep(t->rchild)-deep(t->lchild)>1)
{
if(x>t->rchild->data)
t = RR(t);
else
t = RL(t);
}
}
t->d = max(deep(t->lchild), deep(t->rchild))+1;//每建一个节点将高度更新一遍
return t;
}