平衡二叉树的插入C语言

来源:互联网 发布:linux下创建用户 编辑:程序博客网 时间:2024/05/27 14:13

二叉树的插入主要是考虑到什么时候旋转,什么时候调用旋转函数。还有就是插入一个数他的高度是否变化,bf是否变化。当然在调用递归时左右分开,所以在一定要分开讨论bf的值,与旋转函数调用的时候

#include<stdio.h>#include<stdlib.h>typedef struct BiTre{int data;int bf;struct BiTre *rchild,*lchild;}BiTnood,*BiTree;void R_Rotate(BiTree *p){BiTree l = (*p)->lchild;(*p)->lchild = l->rchild;l->rchild = (*p);(*p) = l;}void L_Rotate(BiTree *p){BiTree l = (*p)->rchild;(*p)->rchild = l->lchild;l->lchild = (*p);(*p)= l;  }void LeftBalance(BiTree *T)//改变左子树的状态 {BiTree L,Lr;L = (*T)->lchild;switch(L->bf){case 1:L->bf=0;(*T)->bf = 0;R_Rotate(T);break;case -1:Lr = L->rchild;switch(Lr->bf){case 0:L->bf=0;(*T)->bf=0;break;case 1:(*T)->bf = 1;L->bf = 0;break;case -1:(*T)->bf = 0;L->bf = -1;break;}Lr->bf = 0;L_Rotate(&((*T)->lchild));R_Rotate(T);}}void RightBalance(BiTree *T)//改变右子树的状态 {BiTree R,Rl;R = (*T)->rchild;switch(R->bf){case -1:(*T)->bf = 0;R->bf = 0;R_Rotate(T);break;case 1:Rl = R->lchild;switch(Rl->bf){case 0:(*T)->bf=0;R->bf=0;break;case 1:(*T)->bf = 0;R->bf = -1;break;case -1:(*T)->bf = 1;R->bf = 0; }Rl->bf=0;R_Rotate(&((*T)->rchild));L_Rotate(T); } } int InsertAVL(BiTree *T,int e,bool *taller)//taller用来判断是否插入成功 0000000000000000000000000000000000000000000000{if(!*T){(*T)= (BiTree)malloc(sizeof(BiTnood));(*T)->bf=0;(*T)->data = e;(*T)->lchild=(*T)->rchild=NULL;*taller = true;}else{if(e==(*T)->data){*taller=0;return false;}if(e<(*T)->data){if(!(InsertAVL(&((*T)->lchild),e,taller))){return false;}if((*taller)==true){switch((*T)->bf){case 0:(*T)->bf = 1;*taller = true;break;case -1:(*T)->bf=0;*taller = false;//没有增加高度break;case 1: LeftBalance(T); *taller = false; break;}}}else{if(!InsertAVL(&((*T)->rchild),e,taller)){return false;}if((*taller)==true){    switch((*T)->bf)    {    case 0:    (*T)->bf=1;    *taller=true;    break;    case 1:    (*T)->bf = 0;    *taller = false;    break;    case -1:     RightBalance(T); *taller = false; break;}}}}}void pre(BiTree T){if(T==NULL)return ;pre(T->lchild);printf("%d ",T->data);pre(T->rchild);}int main(){int a[10]={3,2,7,1,6,7,8,4,5,0};BiTree T;bool taller;for(int i=0;i<10;i++){//printf("df");InsertAVL(&T,a[i],&taller);//printf("%d",T->data);} pre(T);return 0; } 


0 0
原创粉丝点击