#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define LH 1
#define EH 0
#define RH -1
typedef struct BSTNode
{
ElemType data;
int bf;
struct BSTNode* left;
struct BSTNode* right;
}BSTNode,*BSTTree;
void R_Rotate(BSTTree* p)
{
BSTTree lc=(*p)->left;
(*p)->left=lc->right;
lc->right=(*p);
(*p)=lc;
}
void L_Rotate(BSTTree* p)
{
BSTTree rc=(*p)->right;
(*p)->right=rc->left;
rc->left=(*p);
(*p)=rc;
}
void leftBalance(BSTTree* T)
{
BSTTree lc=(*T)->left; BSTTree rd=NULL;
switch(lc->bf)
{
case LH: (*T)->bf=lc->bf=EH;
R_Rotate(T); break;
case RH: rd=lc->right;
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)->left));
R_Rotate(T);
}
}
void rightBalance(BSTTree* T)
{
BSTTree lc=(*T)->right; BSTTree rd=NULL;
switch(lc->bf)
{
case RH: (*T)->bf=lc->bf=EH;
L_Rotate(T); break;
case LH: rd=lc->right;
switch(rd->bf)
{
case LH:(*T)->bf=LH;lc->bf=EH;break;
case EH:(*T)->bf=lc->bf=EH; break;
case RH:(*T)->bf=LH;lc->bf=LH;break;
}
rd->bf=EH;
R_Rotate(&((*T)->right));
L_Rotate(T);
}
}
int insertAVL(BSTTree* T,ElemType e,int* taller)
{
if(!(*T))
{
(*T)=(BSTTree)malloc(sizeof(BSTNode));
(*T)->data=e;
(*T)->left=(*T)->right=NULL;
(*T)->bf=0; *taller=1;
}
else//the AVLtree is not null
{
if(e==(*T)->data) {printf("elemt %d have in the tree\n",e); return 0;}
if(e<(*T)->data)//insert into left child
{
if(!insertAVL(&((*T)->left),e,&(*taller))) return 0;
if(*taller)
{
switch((*T)->bf)
{
case LH: leftBalance(T); *taller=0;break;
case EH: (*T)->bf=LH; *taller=1;break;
case RH: (*T)->bf=EH;*taller=0;break;
}
}
}
else// e>T->data inset into the right child
{
if(!insertAVL(&((*T)->right),e,&(*taller))) {printf(" elemt %d have in the tree\n",e); return 0;}
if(*taller)
{
switch((*T)->bf)
{
case LH: (*T)->bf=EH; *taller=0; break;
case EH: (*T)->bf=RH; *taller=1; break;
case RH: rightBalance(T); *taller=0; break;
}
}
}
}
return 1;
}
int preordertraverse(BSTTree T)
{
if(T)
{
printf("%d\t",T->data);
if(T->left)
{preordertraverse(T->left);}
if(T->right)
{preordertraverse(T->right);}
}
return 0;
}
void inordertraverse(BSTTree T)
{
if(T)
{
if(T->left) inordertraverse(T->left);
printf("%d\t",T->data);
if(T->right) inordertraverse(T->right);
}
return ;
}
int main()
{
BSTTree T=NULL;
int taller=0;
int i=0;
insertAVL(&T,10,&taller);
insertAVL(&T,7,&taller);
insertAVL(&T,19,&taller);
insertAVL(&T,18,&taller);
insertAVL(&T,17,&taller);
insertAVL(&T,15,&taller);
insertAVL(&T,6,&taller);
insertAVL(&T,9,&taller);
insertAVL(&T,11,&taller);
insertAVL(&T,16,&taller);
insertAVL(&T,5,&taller);
insertAVL(&T,4,&taller);
insertAVL(&T,3,&taller);
insertAVL(&T,2,&taller);
insertAVL(&T,1,&taller);
printf("begin traverse\n");
inordertraverse(T);
printf("\nsucess traverse\n");
}