您的位置:首页 > 编程语言 > C语言/C++

Sicily AVL Tree

2016-12-09 16:27 134 查看
Description

给出结点的插入序列,构造AVL Tree。 

 

      

Input

第一行含一个整数t(0<t<10),为测试样例个数。

每个测试样例包含两行;第1行为一个整数n,表示插入的结点数;第2行依照插入顺序给出n个结点的数值(整数),之间用一个空格分隔。

Output

对每个测试样例单独一行输出对应AVL Tree的前序遍历序列,每输出一个结点的数值(包括最后一个结点),其后输出一个空格。 

 

Sample Input


 Copy sample input to clipboard

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


#include<iostream>
using namespace std;
struct node{
int key;
int height;
node* left;
node* right;
};
int getheight(node* temp) {
if (temp == NULL) return 0;
else return temp->height;
}
int max(int a, int b) {
if (a > b) return a;
else return b;
}

//顺时针旋
node* LL(node* root) {
node* p = root->left;
root->left = p->right;
p->right = root;
p->height = max(getheight(root->left), getheight(root->right))+1;
root->height = max(getheight(root->left), getheight(root->right))+1;
return p;
}

//逆时针旋
node* RR(node* root) {
node* p = root->right;
root->right = p->left;
p->left = root;
p->height = max(getheight(root->left), getheight(root->right))+1;
root->height = max(getheight(root->left), getheight(root->right))+1;
return p;
}

node* LR(node* root) {
root->left = RR(root->left);
return LL(root);
}

node* RL(node* root) {
root->right = LL(root->right);
return RR(root);
}

void insert(node* &root, int value) {
if (root == NULL) {
root = new node;
root->key = value;
root->height = 1;
root->left = NULL;
root->right = NULL;
} else {
if (value > root->key) {
insert(root->right, value);
if (getheight(root->right) - getheight(root->left) > 1) {
if (value > root->right->key) root = RR(root);
else root = RL(root);
}
} else if (value < root->key) {
insert(root->left, value);
if (getheight(root->left) - getheight(root->right) > 1) {
if (value < root->left->key) root = LL(root);
else root = LR(root);
}
}
}
root->height = max(getheight(root->right), getheight(root->left)) + 1;
}

void dele(node* root) {
if (root != NULL) {
dele(root->left);
dele(root->right);
delete root;
root = NULL;
}
}

void preorder(node* root) {
if (root != NULL) {
cout << root->key << " ";
preorder(root->left);
preorder(root->right);
}
}

int main() {
int num;
cin >> num;
while(num--) {
int count, temp;
cin >> count;
node* now = NULL;
while(count--) {
cin >> temp;
insert(now, temp);
}
preorder(now);
cout << endl;
dele(now);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Sicily tree c++