6 -1 AVL Insertion(浙大pta)##
6 -1 AVL Insertion
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
AVLTree AVL_Create_node(int Key,AVLTree left,AVLTree right)
{
AVLTree T;
T=(PtrToAVLNode)malloc(sizeof(struct AVLNode));
T->Key=Key;
T->Height=0;
T->Left=left;
T->Right=right;
return T;
}
int Get_height(AVLTree T)
{
if(T==NULL)
return 0;
else
return T->Height;
}
int Get_max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
AVLTree left_left_rotation(AVLTree T2)
{
AVLTree T1;
T1=T2->Left;
T2->Left=T1->Right;
T1->Right=T2;
T1->Height=Get_max(Get_height(T1->Left),Get_height(T2))+1;
T2->Height=Get_max(Get_height(T2->Left),Get_height(T2->Right))+1;
return T1;
}
AVLTree right_right_rotation(AVLTree T2)
{
AVLTree T1;
T1=T2->Right;
T2->Right=T1->Left;
T1->Left=T2;
T1->Height=Get_max(Get_height(T1->Right),Get_height(T2))+1;
T2->Height=Get_max(Get_height(T2->Left),Get_height(T2->Right))+1;
return T1;
}
AVLTree left_right_rotation(AVLTree T)
{
AVLTree Tree;
Tree=T;
T->Left=right_right_rotation(T->Left);
Tree=left_left_rotation(T);
return Tree;
}
AVLTree right_left_rotation(AVLTree T)
{
AVLTree Tree;
Tree=T;
T->Right=left_left_rotation(T->Right);
Tree=right_right_rotation(T);
return Tree;
}
AVLTree Insert(AVLTree T,int Key)
{
if(T==NULL)
{
T=AVL_Create_node(Key,NULL,NULL);
}
else if(T->Key>Key)
{
T->Left=Insert(T->Left,Key);
if(Get_height(T->Left)-Get_height(T->Right)>=2)
{
if(T->Left->Key>Key)
T=left_left_rotation(T);
else
T=left_right_rotation(T);
}
}
else if(T->Key<Key)
{
T->Right=Insert(T->Right,Key);
if(Get_height(T->Right)-Get_height(T->Left)>=2)
{
if(T->Right->Key<Key)
T=right_right_rotation(T);
else
T=right_left_rotation(T);
}
}
T->Height=Get_max(Get_height(T->Left),Get_height(T->Right))+1;
return T;
}