AVL Tree 操作
1.AVL树是带有平衡条件的二叉查找树, 一棵AVL树是其每个节点的左子树和右子树的高度最多差1的二叉查找树。
2.AVL树的删除要比插入复杂。如果删除相对较少,那么用懒惰删除的方法是最好的策略。
3.AVL树的插入操作:
1 #ifndef _AvlTree_H 2 struct AvlNode; 3 typedef struct AvlNode *Position; 4 typedef struct AvlNode *AvlTree; 5 typedef ElementType int; 6 AvlTree Insert(ElmentType X,AvlTree T); 7 AvlTree MakeEmpty(AvlTree T); 8 Position Find(ElementType X,AvlTree T); 9 Position FindMax(AvlTree T); 10 Position FindMin(AvlTree T); 11 AvlTree Delete(ElementType X,AvlTree T); 12 ElementType Retrieve(Position P); 13 #endif; 14 struct AvlNode //定义一个树结构,包含了树的高度 15 { 16 ElementType Element; 17 AvlTree Left; 18 AvlTree Right; 19 int Height; 20 }; 21 int Height(Position P) //取得树的高 22 { 23 if(P==NULL) 24 return -1; 25 else 26 return P->Height; 27 28 } 29 int Max(AvlTree T1, AvlTree T2) //获得大值 30 { 31 if(T1->Height>T2->Height) 32 return T1->Height; 33 else 34 return T2->Height; 35 } 36 37 AvlTree Insert(ElmentType x,AvlTree T) // 树的插入 38 { 39 if(T==NULL) 40 { 41 T=new AvlTree(); 42 T->Element=x; 43 T->Left=NULL; 44 T->Right=NULL; 45 T->Height=0; 46 } 47 else if(x<T->Element) //插入到当前树的左子树中 48 { 49 T->Left=Insert(x,T->Left); 50 if(Height(T->Left)-Height(T->Right)==2)//如果树不平衡 51 { 52 if(x<T->Left->Element) //左左插入只需要进行单旋转 53 T=SingleRotateWithLeft(T); 54 else //左右插入需要进行双旋转,单旋转不能改变去不平衡的状态 55 T=DoubleRotateWithLeft(T); 56 } 57 } 58 else if(x>T->Element)//插入到当前树的右子树中 59 { 60 T->Right=Insert(x,T->Right); 61 if(Height(T->Right)-Height(T->Left)==2) 62 { 63 if(x>T->Right->Element) //右右插入只需要进行单旋转 64 T=SingleRotateWithRight(T); 65 else //右左插入需要进行双旋转,单旋转不能改变去不平衡的状态 66 T=DoubleRotateWithRight(T); 67 } 68 } 69 else{cout<<"error:不能插入相同的树结点"}; 70 T->Height=Max(Height(T->Left),Height(T->Right))+1; 71 return T; 72 } 73 74 Position singleRotateWithLeft(Position K2)//左左单旋 75 { 76 Position K1; 77 K1=K2->Left; 78 K2->Left=K1->Right; 79 K1->Right=K2; 80 K2->Height=Max(Height(K2->Left),Height(K2->Right))+1; 81 K1->Height=Max(Height(K1->Left),Height(K1->Right))+1; 82 return K1; 83 } 84 Position singleRotateWithRight(Position K2)//右右单旋 85 { 86 Position K1; 87 K1=K2->Right; 88 K2->Right=K1->Left; 89 K1->Left=K2; 90 K2->Height=Max(Height(K2->Left),Height(K2->Right)+1; 91 K1->Height=Max(Height(K1->Left),Height(K1->Right))+1; 92 return K1; 93 } 94 Position DoubleRotateWithLeft(Position K3)//左右双旋 95 { 96 Position K1,K2; 97 K2=K3->Left; 98 K1=K2->Right; 99 k2->Right=K1->Left; 100 K3->Left=K1->Right; 101 K1->Left=K2; 102 K1->Right=K3; 103 104 K1->Height=Max(Height(K1->Left),Height(K1->Right))+1; 105 K2->Height=Max(Height(K2->Left),Height(K2->Right)+1; 106 K3->Height=Max(Height(K3->Left),Height(K3->Right)+1; 107 108 } 109 110 Position DoubleRotateWithRight(Position K3)//右左双旋 111 { 112 //Rotate between k1 and K2; 113 K3->Right=singleRotateWithLeft(K3->Right); 114 //Rotate between k2 and k3; 115 return singleRotateWithRight(K3); 116 117 }