1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include<stdio.h> #include<malloc.h> struct Node{ int value; int height; struct Node* child[2]; }; int Height(struct Node* now){ return now==NULL?0:now->height; } int max(const int a,const int b){ return a>b?a:b; } void freshHeight(struct Node* now){ now->height=1+max(Height(now->child[0]),Height(now->child[1])); } void rotate(struct Node* parent,struct Node* now,int pos,int direction){ struct Node *newroot=now->child[!direction]; if(parent!=NULL)parent->child[pos]=newroot; now->child[!direction]=newroot->child[direction]; newroot->child[direction]=now; freshHeight(now); freshHeight(newroot); if(parent!=NULL)freshHeight(parent); } int checkBalance(struct Node* now,int *flag,int *twice){ if(Height(now->child[0])-Height(now->child[1])==2){ *flag=0; } else if(Height(now->child[1])-Height(now->child[0])==2){ *flag=1; } else return 0; *twice=Height(now->child[*flag]->child[*flag])<Height(now->child[*flag]->child[!(*flag)]); return 1; } void reBalance(struct Node* parent,struct Node* now,int pos){ int rotateflag,twiceflag,flag; flag=checkBalance(now,&rotateflag,&twiceflag); if(flag){ if(twiceflag)rotate(now,now->child[rotateflag],rotateflag,rotateflag); rotate(parent,now,pos,!rotateflag); } } void insert(struct Node *now,int value){ int pos=now->value<value; if(now->child[pos]==NULL){ now->child[pos]=(struct Node*)malloc(sizeof(struct Node)); now->child[pos]->value=value; now->child[pos]->child[0]=now->child[pos]->child[1]=NULL; now->child[pos]->height=1; } else{ insert(now->child[pos],value); reBalance(now,now->child[pos],pos); } freshHeight(now); } void destroy(struct Node* now){ if(now->child[0]!=NULL)destroy(now->child[0]); if(now->child[1]!=NULL)destroy(now->child[1]); free(now); } void preOrderTransverse(struct Node* now){ printf("%d,",now->value); if(now->child[0]!=NULL)preOrderTransverse(now->child[0]); if(now->child[1]!=NULL)preOrderTransverse(now->child[1]); } int main(){ struct Node* root=(struct Node*)malloc(sizeof(struct Node)); root->child[0]=root->child[1]=NULL; root->height=1; scanf("%d,",&(root->value)); int value; while(scanf("%d,",&value)!=EOF){ insert(root,value); } preOrderTransverse(root); destroy(root); return 0; }
|