标签:
待我在看看
#include<cstdio> #include<cstdlib> #include<cstring> #define LH +1 #define EH 0 #define RH -1 typedef struct BiTNode{ int data; int bf; //结点的平衡因子 struct BiTNode *lchild,*rchild; }BiTNode,*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,Ll; L = (*T)->rchild; switch(L->bf){ case RH: (*T)->bf = L->bf = EH; L_Rotate(T); break; case LH: Ll = L->lchild; switch(Ll->bf){ case LH: (*T)->bf = RH; L->bf = EH; break; case EH: (*T)->bf = L->bf = EH; break; case RH: (*T)->bf = RH; L->bf = EH; break; } Ll->bf = EH; R_Rotate(&(*T)->rchild); L_Rotate(T); } } int InsertAVL(BiTree *T,int e,int *taller){ if(!(*T)){ *T = (BiTree)malloc(sizeof(BiTNode)); (*T)->data = e; (*T)->lchild = (*T)->rchild = NULL; (*T)->bf = EH; *taller = 1; }else{ if(e == (*T)->data){ *taller = 0; return 0; }else if(e < (*T)->data){ if(!InsertAVL(&(*T)->lchild,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{ if(!InsertAVL(&(*T)->rchild,e,taller)) return 0; if(*taller){ switch((*T)->bf){ case LH: (*T)->bf = EH; *taller = false; break; case EH: (*T)->bf = RH; *taller = 1; break; case RH: RightBalance(T); *taller = 0; break; } } } } } void InOrderTraverse(BiTree T) { if (T == NULL) { return; } InOrderTraverse(T->lchild);//访问左子树 printf("%d ",T->data);//访问根结点 InOrderTraverse(T->rchild);//访问右子树 } int main(){ int i; int a[] = {3,2,1,4,5,6,7,10,9,8,25,13,46,26,68,98,15,12}; BiTree T = NULL; int taller; for (i=0; i<18; i++) { InsertAVL(&T,a[i],&taller); } InOrderTraverse(T); printf("\n"); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhuozhuo/p/5427894.html