AVL Insertion (30 分)
You are supposed to implement the Insert
function, which inserts an integer Key
into an AVL tree T
. The resulting tree must be returned.
Format of function:
AVLTree Insert ( AVLTree T, int Key );
where AVLTree
is defined as the following:
typedef struct AVLNode *PtrToAVLNode;
struct AVLNode{
int Key;
PtrToAVLNode Left;
PtrToAVLNode Right;
int Height;
};
typedef PtrToAVLNode AVLTree;
Sample program of judge:
#include <stdio.h>
#include <stdlib.h>
typedef struct AVLNode *PtrToAVLNode;
struct AVLNode{
int Key;
PtrToAVLNode Left;
PtrToAVLNode Right;
int Height;
};
typedef PtrToAVLNode AVLTree;
AVLTree Insert ( AVLTree T, int Key );
void PostOrderPrint( AVLTree T ); /* details omitted */
void InOrderPrint( AVLTree T ); /* details omitted */
int main()
{
int N, Key, i;
AVLTree T = NULL;
scanf("%d", &N);
for ( i=0; i<N; i++ ) {
scanf("%d", &Key);
T = Insert( T, Key );
}
PostOrderPrint( T );
InOrderPrint( T );
return 0;
}
/* Your function will be put here */
Sample Input:
7
88 70 61 96 120 90 65
Sample Output:
Post-order: 61 70 65 90 120 96 88
In-order: 61 65 70 88 90 96 120
int height(AVLTree T) {
AVLTree lc = T->Left;
AVLTree rc = T->Right;
if (rc == NULL&&lc == NULL) return 1;
else if (rc == NULL&&lc != NULL) return lc->Height + 1;
else if (rc != NULL&&lc == NULL) return rc->Height + 1;
else {
if (rc->Height > lc->Height) return rc->Height + 1;
else return lc->Height + 1;
}
}
int judge(AVLTree T) {
int rc = 0, lc = 0;
if (T->Left != NULL) lc = T->Left->Height;
if (T->Right != NULL) rc = T->Right->Height;
return lc - rc;
}
AVLTree Insert(AVLTree T, int Key) {
if (T == NULL) {
T = (AVLTree)malloc(sizeof(struct AVLNode));
T->Left = T->Right = NULL; T->Key = Key; T->Height = 1;
}
else {
if (T->Key > Key) T->Left = Insert(T->Left, Key);
else if (T->Key < Key) T->Right = Insert(T->Right,Key);
T->Height = height(T);
if (judge(T) > 1) {
AVLTree lc = T->Left;
if (judge(lc) >0) { //LL
T->Left = lc->Right;
lc->Right = T;
T = lc;
T->Right->Height = height(T->Right);
}
else if(judge(lc) <0){ //LR
AVLTree rc = lc->Right;
lc->Right = rc->Left;
rc->Left = lc;
lc = rc;
T->Left = lc->Right;
lc->Right = T;
T = lc;
T->Left->Height = height(T->Left);
T->Right->Height = height(T->Right);
} T->Height = height(T);
}
else if (judge(T)<-1) {
AVLTree rc = T->Right;
if (judge(rc) >0) { //RL
AVLTree lc = rc->Left;
rc->Left = lc->Right;
lc->Right = rc;
rc = lc;
T->Right = rc->Left;
rc->Left = T;
T = rc;
T->Left->Height = height(T->Left);
T->Right->Height = height(T->Right);
}
else if (judge(rc) <0) { //RR
T->Right = rc->Left;
rc->Left = T;
T = rc;
T->Left->Height = height(T->Left);
}T->Height = height(T);
}
}
return T;
}