1 typedef struct avltreenode *avltree; 2 typedef struct avltreenode{ 3 int data; 4 avltree left; 5 avltree right; 6 int height; 7 }; 8 9 int getheight(avltree a) 10 { 11 if(a==NULL) return -1; 12 return a->height; 13 } 14 15 //a必须有一个左子结点b 16 //a与b做左单旋,更新a与b高度,返回新的根结点b 17 avltree singleleftrotation(avltree a) 18 { 19 avltree b=a->left; 20 a->left=b->right; 21 b->right=a; 22 a->height=max(getheight(a->left),getheight(a->right))+1; 23 b->height=max(getheight(b->left),a->height)+1; 24 25 return b; 26 } 27 28 //右单旋 29 avltree singlerightrotation(avltree a) 30 { 31 avltree b=a->right; 32 a->right=b->left; 33 b->left=a; 34 35 a->height=max(getheight(a->left),getheight(a->right))+1; 36 b->height=max(getheight(b->right),a->height)+1; 37 38 return b; 39 } 40 41 //左右双旋 42 //a必须有一个左子结点b,且b必须有一个右子结点c 43 //a,b,c,做两次单旋,返回新的根结点c 44 //先对b和c做右单旋,在对a和c做左单旋 45 avltree doubleleftrightrotation(avltree a) 46 { 47 a->left=singlerightrotation(a->left); 48 49 return singleleftrotation(a); 50 } 51 52 //右左双旋 53 avltree doublerightleftrotation(avltree a) 54 { 55 a->right=singleleftrotation(a->right); 56 57 return singlerightrotation(a); 58 } 59 60 avltree avl_insertion(int x,avltree t) 61 { 62 /*将X插入avl树T中,并返回调整后的avl树*/ 63 if(!t)/*插入空树,则新建包含一个结点的树*/ 64 { 65 t=(avltree)malloc(sizeof(struct avltreenode)); 66 t->data=x; 67 t->height=0; 68 t->left=t->right=NULL; 69 }/*插入空树结束*/ 70 else if(x<t->data) 71 { 72 t->left=avl_insertion(x,t->left); 73 if(getheight(t->left)-getheight(t->right)==2) 74 { 75 /*需要左旋*/ 76 if(x<t->left->data) 77 t=singleleftrotation(t);//左单旋 singleleftrotation 78 else 79 t=doubleleftrightrotation(t);//左右双旋 80 } 81 } 82 else if(x>t->data) 83 { 84 t->right=avl_insertion(x,t->right); 85 if(getheight(t->left)-getheight(t->right)==-2) 86 { 87 /*需要右旋*/ 88 if(x>t->right->data) 89 t=singlerightrotation(t);//右单旋 90 else 91 t=doublerightleftrotation(t);//右左双旋 92 } 93 } 94 95 //x=data,无须插入 96 t->height=max(getheight(t->left),getheight(t->right))+1; 97 return t; 98 }
例题:pat1066
代码:pat1066ac代码
时间: 2024-10-22 14:51:01