Sicily AVL Tree

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);
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值