|
发表于 2021-12-3 00:47:47
|
显示全部楼层
本帖最后由 1569044682 于 2021-12-3 00:51 编辑
最后两行注释是测试用例
#include <stdio.h>
#include <stdlib.h>
#define LH 1
#define EH 0
#define RH -1
typedef struct BTNode{
int data;
int bf;
struct BTNode * lchild;
struct BTNode * rchild;
}*BiTree;
void R_Rotate(BiTree *p)
{
BiTree L;
L = (*p)->lchild;
(*p)->lchild = L->rchild;
L->rchild = (*p);
*p = L;
}
void L_Rotate(BiTree *p)
{
BiTree R;
R = (*p)->rchild;
(*p)->rchild = R->lchild;
R->lchild = (*p);
*p = R;
}
void LeftBalance(BiTree *T)
{
BiTree L,Lr;
L = (*T)->lchild;
switch(L->bf)
{
case LH:
(*T)->bf = L->bf = EH;
R_Rotate(T);
break;
case RH:
Lr = L->rchild;
switch(Lr->bf)
{
case LH:
(*T)->bf = RH;
L->bf = EH;
break;
case EH:
(*T)->bf = L->bf = EH;
break;
case RH:
(*T)->bf = EH;
L->bf = LH;
break;
}
Lr->bf = EH;
L_Rotate(&(*T)->lchild);
R_Rotate(T);
}
}
void RightBalance(BiTree *T)
{
BiTree L,Lr;
L=(*T)->rchild;
switch(L->bf)
{
case RH:
(*T)->bf=L->bf=EH;
L_Rotate(T);
break;
case LH:
Lr=L->lchild;
switch(Lr->bf)
{
case RH:
(*T)->bf=LH;
L->bf=EH;
break;
case EH:
(*T)->bf=L->bf=EH;
break;
case LH:
(*T)->bf=EH;
L->bf=RH;
break;
}
Lr->bf=EH;
R_Rotate(&(*T)->rchild);
L_Rotate(T);
}
}
int InsertAVL(BiTree *T, int e, int *taller)
{
if( !(*T) )
{
*T = (BiTree)malloc(sizeof(BiTree));
(*T)->data = e;
(*T)->lchild = (*T)->rchild = NULL;
(*T)->bf = EH;
*taller = true;
}
else
{
if(e == (*T)->data)
{
*taller = false;
return false;
}
if(e < (*T)->data)
{
if(!InsertAVL(&(*T)->lchild, e, taller))
{
return true;
}
if(*taller)
{
switch((*T)->bf)
{
case LH:
LeftBalance(T);
*taller = false;
break;
case EH:
(*T)->bf = LH;
*taller = true;
break;
case RH:
(*T)->bf = EH;
*taller = false;
break;
}
}
}
else
{
if(!InsertAVL(&(*T)->rchild, e, taller))/**/
{
return false;
}
if(*taller)
{
switch((*T)->bf)
{
case LH:
(*T)->bf = EH;
*taller = false;
break;
case EH:
(*T)->bf = RH;
*taller = true;
break;
case RH:
RightBalance(T);
*taller = false;
break;
}
}
}
}
return true;
}
void printBIT( BiTree root, int x)
{
if (root != NULL)
{
printBIT(root->lchild, x + 1);
for (int i = 0; i < x; i++)
{
printf(" ");
}
printf("%d\n",root->data);
printBIT(root->rchild, x + 1);
}
}
void Inorder( BiTree BT )//中序遍历
{
if( BT == NULL ){
return ;
}
Inorder( BT->lchild );
printf(" %d", BT->data);
Inorder( BT->rchild );
}
int main()
{
int n=0,i=0,e,taller = 0;
char c;
BiTree T=NULL;
while(1)
{
scanf("%d",&e);
if(e == 0){
break;
}
InsertAVL( &T,e,&taller );
}
printf("中序遍历结果:\n");
Inorder( T );
printf("\n二叉树凹入表示:\n");
printBIT( T,0 );
printf("\n");
return 0;
}
//56 78 34 89 12 35 67 77 22 57 0
//147 106 291 130 71 51 7 202 94 249 132 24 85 0 |
|