数据结构算法:平衡二叉树实现代码(3)
发布时间:2010/11/10 15:29:27 来源:www.xue.net 编辑:城市总裁吧
bitree *createsuperbitree(int *source,int len)/*不消说了,建立平衡二叉树*/
{
int itemp;
bitree *head=NULL;
bitree *temp=NULL;
bitree *tmother=NULL;
bitree *p=NULL;
bitree *q=NULL;
head=(bitree *)malloc(sizeof(bitree));
head->lchild=NULL;
head->rchild=NULL;
head->item=*source;
head->bdegree=0;
source++;
len--;
while(len>0)
{
insertbitree(head,*source);
addbdegree(head);
temp=leveldetect(head);
if(temp!=NULL)
{
tmother=getmother(head,temp);
if(temp->bdegree==2 && temp->lchild!=NULL && temp->lchild->bdegree==1)
{
p=temp->lchild;
temp->lchild=p->rchild;
p->rchild=temp;
if(tmother!=NULL)
{
if(tmother->lchild==temp)tmother->lchild=p;
else tmother->rchild=p;
}
else
head=p;
}/*LL*/
if(temp->bdegree==2 && temp->lchild!=NULL && temp->lchild->bdegree==-1)
{
p=temp->lchild->rchild;
q=temp->lchild;
q->rchild=p->lchild;
temp->lchild=p->rchild;
p->lchild=q;
p->rchild=temp;
if(tmother!=NULL)
{
if(tmother->lchild==temp)tmother->lchild=p;
else tmother->rchild=p;
}
else
head=p;
}/*LR*/
if(temp->bdegree==-2 && temp->rchild!=NULL && temp->rchild->bdegree==-1)
{
p=temp->rchild;
temp->rchild=p->lchild;
p->lchild=temp;
if(tmother!=NULL)
{
if(tmother->lchild==temp)tmother->lchild=p;
else tmother->rchild=p;
}
else
head=p;
}/*RR*/
if(temp->bdegree==-2 && temp->rchild!=NULL && temp->rchild->bdegree==1)
{
p=temp->rchild->lchild;
q=temp->rchild;
temp->rchild=p->lchild;
q->lchild=p->rchild;
p->lchild=temp;
p->rchild=q;
if(tmother!=NULL)
{
if(tmother->lchild==temp)tmother->lchild=p;
else tmother->rchild=p;
}
else
head=p;
}/*RL*/
addbdegree(head);
}
source++;
len--;
}
return head;
}
main()/*演示*/
{
int binums[100],i,len;
bitree *head,*temp;
for(i=0;i<=99;i++)binums[i]=0;
len=getnums(binums);
head=createsuperbitree(binums,len);
temp=getmother(head,head->rchild->rchild->rchild);
}