AVL Tree

Description

Input

Output

Sample Input
2
5
1 2 3 5 4
16
3 2 1 4 5 6 7 16 15 14 13 12 11 10 8 9

Sample Output
2 1 4 3 5
7 4 2 1 3 6 5 13 11 9 8 10 12 15 14 16

// Problem#: 19591
// Submission#: 4960420
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <iostream>
using namespace std;
#define DataType int
/*

*/
typedef struct AvlNode{
DataType    data;
AvlNode    * left;
AvlNode    * right;
int height;
}*AvlTree,AvlNode;

//求两个数的最大值
int Max(int a,int b) {
return a>b?a:b;
}
//求树的高度
int Height( AvlTree T) {
if(NULL == T)
return -1;
else
return T->height;
}

//单旋转右旋
AvlTree singleRotateWithRight(AvlTree T) {
AvlTree L = T->left;
T->left = L->right;
L->right = T;
T->height = Max( Height(T->left),Height(T->right) ) + 1;
L->height = Max( Height(L->left),Height(L->right) ) + 1;
return L;
}
//单旋转左旋
AvlTree singleRotateWithLeft(AvlTree T) {
AvlTree R = T->right;
T->right = R->left;
R->left = T;
T->height = Max( Height(T->left),Height(T->right) ) + 1;
R->height = Max( Height(R->left),Height(R->right) ) + 1;
return R;
}
//双旋转，先左后右
AvlTree doubleRotateWithLeft(AvlTree T) {
T->left = singleRotateWithLeft(T->left);
return singleRotateWithRight(T);
}
//双旋转，先右后左
AvlTree doubleRotateWithRight(AvlTree T) {
T->right = singleRotateWithRight(T->right);
return singleRotateWithLeft(T);
}
AvlTree AvlTreeInsert(AvlTree T, DataType x) {
if(T == NULL) {
T = new AvlNode;
if(T) {
T->data = x;
T->left    = NULL;
T->right = NULL;
T->height = 0;
} else {
exit(0);
}
}
else if( x < T->data) {
T->left = AvlTreeInsert(T->left,x);    //先插入，后旋转
if(Height(T->left) - Height(T->right) == 2) {
if(x < T->left->data) {
T = singleRotateWithRight( T );
} else {   //左右情况，双旋转,先左
T = doubleRotateWithLeft( T );
}
}
}
else if( x > T->data ) {
T->right = AvlTreeInsert(T->right,x);
if(Height(T->right) - Height(T->left) == 2) {
if(x > T->right->data) {  //右右情况，进行左旋
T = singleRotateWithLeft( T );
} else {
T = doubleRotateWithRight( T );
}
}
}
//如果这个数已经存在，那么不进行插入
T->height = Max(Height(T->left),Height(T->right)) + 1;
return T;
}
//前序遍历
void PrevOrderVisitUseRecur(const AvlTree pCurrent) {
if(pCurrent) {
cout << pCurrent->data << " ";
PrevOrderVisitUseRecur(pCurrent->left);
PrevOrderVisitUseRecur(pCurrent->right);
}
}
// 删除
void clear(AvlTree root) {
if (root == NULL) return;
clear(root->left);
clear(root->right);
delete root;
}
int main() {
int t, n, temp;
AvlTree root = NULL;
cin>> t;
while (t--) {
cin>> n;
for (int i= 0; i< n; i++) {
cin>> temp;
root = AvlTreeInsert(root, temp);
}
PrevOrderVisitUseRecur(root);
cout<< endl;
clear(root);
root = NULL;
}
return 0;
}                                 

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客