5
88 70 61 96 120
7
88 70 61 96 120 90 65
1.代码
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct AVLNode * Position;
typedef Position AVLTree;
struct AVLNode{
ElementType Data;
AVLTree Left;
AVLTree Right;
int Height;
};
int Max(int a, int b){
return a>b ? a : b;
}
int GetHeight(AVLTree T){
int HL, HR, MaxH=0;
if(T){
HL = GetHeight(T->Left);
HR = GetHeight(T->Right);
MaxH = Max(HL, HR);
return(MaxH+1);
}
else
return 0;
}
AVLTree SingleLeftRotation(AVLTree A){
AVLTree B = A->Left;
A->Left = B->Right;
B->Right = A;
A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;
B->Height = Max( GetHeight(B->Left), A->Height ) + 1;
return B;
}
AVLTree SingleRightRotation(AVLTree A){
AVLTree B = A->Right;
A->Right = B->Left;
B->Left = A;
A->Height = Max( GetHeight(A->Left), GetHeight(A->Right) ) + 1;
B->Height = Max( GetHeight(B->Left), A->Height ) + 1;
return B;
}
AVLTree DoubleLeftRightRotation ( AVLTree A )
{ /* 注意:A必须有一个左子结点B,且B必须有一个右子结点C */
/* 将A、B与C做两次单旋,返回新的根结点C */
/* 将B与C做右单旋,C被返回 */
A->Left = SingleRightRotation(A->Left);
/* 将A与C做左单旋,C被返回 */
return SingleLeftRotation(A);
}
AVLTree DoubleRightLeftRotation ( AVLTree A )
{
/* 将B与C做左单旋,C被返回 */
A->Right = SingleLeftRotation(A->Right);
/* 将A与C做右单旋,C被返回 */
return SingleRightRotation(A);
}
AVLTree Insert(AVLTree T, ElementType X){
if(!T){
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Data = X;
T->Height = 1;
T->Left = T->Right = NULL;
}
else if(X < T->Data){
T->Left = Insert(T->Left, X);
if(GetHeight(T->Left)-GetHeight(T->Right) == 2){
if(X<T->Left->Data)
T = SingleLeftRotation(T);
else
T = DoubleLeftRightRotation(T);
}
}
else if(X > T->Data){
//printf("three");
T->Right = Insert(T->Right, X);
if(GetHeight(T->Left)-GetHeight(T->Right) == -2){
if(X>T->Right->Data)
T = SingleRightRotation(T);
else
T = DoubleRightLeftRotation(T);
}
}
T->Height = Max( GetHeight(T->Left), GetHeight(T->Right) ) + 1;
return T;
}
int main(){
int N, i, v;
AVLTree T = NULL;
scanf("%d", &N);
for(i=0; i<N; i++){
scanf("%d", &v);
T = Insert(T, v);
}
printf("%d", T->Data);
return 0;
}
2.小结
- 代码运行的时候一直只能够插入一个元素,最后我才发现
T->Left = Insert(T, X); //正确的是 Insert(T->Left , X)