AVL树指针版参考代码 算法导论
数据结构定义
typedef struct BITNode{ int data; int bf; int cnt; struct BITNode *lchild,*rchild; }BITNode,*BITree;
左旋
void L_Rotate(BITree &T) { BITree tmp; tmp=T->rchild; T->rchild=tmp->lchild; tmp->lchild=T; T=tmp; }
右旋
void R_Rotate(BITree &T) { BITree tmp; tmp=T->lchild; T->lchild=tmp->rchild; tmp->rchild=T; T=tmp; }
右平衡,右子树超重
void RightBalance(BITree &T) { BITree tmp,tmpr; tmp=T->rchild; switch(tmp->bf) { case -1: { T->bf=0; tmp->bf=0; L_Rotate(T); break; } case 1: { tmpr=tmp->lchild; switch (tmpr->bf) { case 1: { tmp->bf=-1; T->bf=0; break; } case -1: { tmp->bf=0; T->bf=1; break; } case 0: { tmp->bf=T->bf=0; } } tmpr->bf=0; R_Rotate(T->rchild); L_Rotate(T); } } }
左平衡
void LeftBlance(BITree &T) { BITree tmp,tmpr; tmp=T->lchild; switch(tmp->bf) { case 1: { T->bf=0; tmp->bf=0; R_Rotate(T); break; } case -1: { tmpr=tmp->rchild; switch(tmpr->bf) { case 1: { tmp->bf=0; T->bf=-1; break; } case -1: { tmp->bf=1; T->bf=0; break; } case 0: { T->bf=0; tmp->bf=0; break; } } tmpr->bf=0; L_Rotate(T->lchild); R_Rotate(T); } } }
插入
bool insertAVL(BITree &T,int key,bool &taller) { if(T==NULL) { T=(BITree) malloc(sizeof(BITNode)); T->data=key; T->lchild=T->rchild=NULL; T->bf=0; T->cnt=1; taller=true; return true; } else if((T)->data==key) { taller=false; T->cnt++; return false; } else if(T->data>key) { if (!insertAVL(T->lchild,key,taller)) return false; if(taller) { switch (T->bf) { case 1: { LeftBlance(T); taller=false; break; } case 0: { T->bf=1; taller=true; break; } case -1: { T->bf=0; taller=false; break; } } } } else { if(!insertAVL(T->rchild,key,taller)) return false; if (taller) { switch(T->bf) { case 1: { T->bf=0; taller=false; break; } case 0: { T->bf=-1; taller=true; break; } case -1: { RightBalance(T); taller=false; } } } } return true; }
中序遍历
void inOrder(BITree r) { if (r==NULL) return ; inOrder(r->lchild); for (int i=0;i<r->cnt;i++) cout<<r->data<<" "; inOrder(r->rchild); }