标签:
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
这道题比较简单 只要你搞懂 avl树 就没什么问题
看懂题目给的图很关键
关于avl树可以看我的另一篇博文 http://www.cnblogs.com/threezj/p/4509852.html
下面给出ac代码
1 #include "stdio.h" 2 #include "stdlib.h" 3 typedef struct AVLTreeNode *AVLTree; 4 5 typedef struct AVLTreeNode{ 6 int Data; 7 AVLTree Left; 8 AVLTree Right; 9 int Height; 10 }; 11 12 AVLTree SingleRightRotation(AVLTree A); 13 AVLTree DoubleLeftRightRotation(AVLTree A); 14 AVLTree SingleLeftRotation(AVLTree A); 15 AVLTree DoubleRightLeftRotation(AVLTree A); 16 int GetHeight(AVLTree bt); 17 int Max(int a,int b); 18 AVLTree AVL_Insertion(int x,AVLTree t); 19 20 int main() 21 { 22 AVLTree t; 23 int i,n,data; 24 t=(AVLTree)malloc(sizeof(struct AVLTreeNode)); 25 t=NULL; 26 scanf("%d",&n); 27 28 for(i=0;i<n;i++) 29 { 30 scanf("%d",&data); 31 t=AVL_Insertion(data,t); 32 } 33 printf("%d",t->Data); 34 } 35 36 37 int GetHeight(AVLTree bt) 38 { 39 if(bt==NULL) 40 return 0; 41 return (bt->Height); 42 } 43 int Max(int a,int b) 44 { 45 return a>b?a:b; 46 } 47 AVLTree AVL_Insertion(int x,AVLTree t) 48 { 49 if(!t) 50 { 51 t=(AVLTree)malloc(sizeof(struct AVLTreeNode)); 52 t->Data=x; 53 t->Height=0; 54 t->Left=t->Right=NULL; 55 } 56 else if(x<t->Data) 57 { 58 t->Left=AVL_Insertion(x,t->Left); //若x比data小,则插到左子树 59 if(GetHeight(t->Left)-GetHeight(t->Right)==2) //若平衡因子为2,则这个节点的平衡被破坏 60 if(x<t->Left->Data) //破坏者在左子树的左子树 则右旋转 61 t=SingleRightRotation(t); 62 else 63 t=DoubleLeftRightRotation(t); //在左子树的右子树 则进行LR旋转 先左旋再右旋 64 } 65 else if(x>t->Data) 66 { 67 t->Right=AVL_Insertion(x,t->Right); 68 if(GetHeight(t->Left)-GetHeight(t->Right)==-2) 69 if(x>t->Right->Data) 70 t=SingleLeftRotation(t); //在右子树的右子树 进行左旋 71 else 72 t=DoubleRightLeftRotation(t); //右子树的左子树 进行RL旋转 73 74 } 75 t->Height=Max(GetHeight(t->Left),GetHeight(t->Right))+1; //更新高度 76 77 return t; 78 } 79 80 AVLTree SingleRightRotation(AVLTree A) 81 { 82 AVLTree B=A->Left; //a的左子树给B 83 A->Left=B->Right; //把b的右子树放到a的左边 84 B->Right=A; //a放到b的右边 85 A->Height=Max(GetHeight(A->Left),GetHeight(A->Right))+1; 86 B->Height=Max(GetHeight(B->Left),A->Height)+1; 87 return B; 88 } 89 90 AVLTree DoubleLeftRightRotation(AVLTree A) 91 { 92 A->Left=SingleLeftRotation(A->Left); 93 94 return SingleRightRotation(A); 95 } 96 97 AVLTree SingleLeftRotation(AVLTree A) 98 { 99 AVLTree B=A->Right; 100 A->Right=B->Left; 101 B->Left=A; 102 A->Height=Max(GetHeight(A->Left),GetHeight(A->Right))+1; 103 B->Height=Max(GetHeight(B->Right),A->Height)+1; 104 return B; 105 } 106 107 AVLTree DoubleRightLeftRotation(AVLTree A) 108 { 109 A->Right=SingleRightRotation(A->Right); 110 111 return SingleLeftRotation(A); 112 }
标签:
原文地址:http://www.cnblogs.com/threezj/p/4520572.html