#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define LH +1
#define EH 0
#define RH -1
typedef int ElemType;
typedef int Boolean;
typedef struct BSTNode{
ElemType data;
int bf; // 结点的平衡因子
struct BSTNode *lchild, *rchild;
}BSTNode, *BSTree;
void R_Rotate( BSTree *T );
void L_Rotate( BSTree *T );
void LeftBalance( BSTree *T );
void RightBalance( BSTree *T );
int InsertAVL( BSTree *T, ElemType e, Boolean *taller );
void R_Rotate( BSTree *T )
{
BSTree lc;
lc = (*T)->lchild;
(*T)->lchild = lc->rchild;
lc->rchild = *T;
*T = lc;
}
void L_Rotate( BSTree *T )
{
BSTree rc;
rc = (*T)->rchild;
(*T)->rchild = rc->lchild;
rc->lchild = *T;
*T = rc;
}
void LeftBalance( BSTree *T )
{
BSTree lc;
BSTree rd;
lc = (*T)->lchild;
switch( lc->bf)
{
case LH:
(*T)->bf = lc->bf = EH;
R_Rotate(T);
break;
case RH:
rd = lc->rchild;
switch( rd->bf)
{
case LH:
(*T)->bf = RH;
lc->bf = EH;
break;
case EH:
(*T)->bf = lc->bf = EH;
break;
case RH:
(*T)->bf = EH;
lc->bf = LH;
break;
}
rd->bf = EH;
L_Rotate( &(*T)->lchild );
R_Rotate( T );
}
}
void RightBalance( BSTree *T )
{
BSTree rc = (*T)->rchild;
BSTree ld = rc->lchild;
switch( rc->bf )
{
case LH:
switch( ld->bf )
{
case LH:
(*T)->bf = EH;
rc->bf = RH;
break;
case EH:
(*T)->bf = rc->bf = EH;
break;
case RH:
(*T)->bf = LH;
rc->bf = EH;
break;
}
ld->bf = EH;
R_Rotate( &(*T)->rchild );
L_Rotate( T );
}
}
int InsertAVL( BSTree *T, ElemType e, Boolean *taller )
{
if( !(*T) )
{
*T = (BSTree) malloc( sizeof( BSTNode ) );
(*T)->data = e;
(*T)->lchild = (*T)->rchild = NULL;
(*T)->bf = EH;
*taller = TRUE;
}
else
{
if( e == (*T)->data )
{
*taller = FALSE;
return 0;
}
if( (*T)->data > e )
{
if( !InsertAVL( &(*T)->lchild, e, taller) )
return 0;
if( *taller )
{
switch( (*T)->bf )
{
case LH:
LeftBalance( T );
*taller = FALSE;
break;
case EH:
(*T)->bf = LH;
break;
case RH:
(*T)->bf = EH;
*taller = FALSE;
}
}
}
else
{
if( !InsertAVL( &(*T)->rchild, e, taller) )
{
taller = FALSE;
return 0;
}
if( *taller )
{
switch( (*T)->bf )
{
case LH:
(*T)->bf = EH;
*taller = FALSE;
break;
case EH:
(*T)->bf = RH;
break;
case RH:
RightBalance( T );
*taller = FALSE;
break;
}//switch
}//if
}//else
}//else
return TRUE;
}
int main()
{
int a[ 5 ];
int i = 0;
BSTree p = NULL;
int taller;
printf( "input number:\n" );
for( ; i < 5; i++ )
scanf( "%d", &a[i] );
for( i = 0; i < 5; i++ )
{
taller = FALSE;
if( !InsertAVL( &p, a[i], &taller ) )
printf( "%d is exist!\n", a[i] );
}
return 0;
}
C语言里没有引用传递,所以要使修改函数的指针参数,必须使用指针的指针。运算符优先级: ‘->'大于'*' 大于‘&’。