Sicily AVL Tree
来源:互联网 发布:编程器diy 编辑:程序博客网 时间:2024/06/10 08:15
Description
给出结点的插入序列,构造AVL Tree。
Input
第一行含一个整数t(0<t<10),为测试样例个数。
每个测试样例包含两行;第1行为一个整数n,表示插入的结点数;第2行依照插入顺序给出n个结点的数值(整数),之间用一个空格分隔。
Output
对每个测试样例单独一行输出对应AVL Tree的前序遍历序列,每输出一个结点的数值(包括最后一个结点),其后输出一个空格。
Sample Input
251 2 3 5 4163 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 0
- Sicily 3825. AVL Tree
- Sicily AVL Tree
- AVL Tree
- AVL- tree
- avl tree
- AVL Tree
- AVL-TREE
- AVL Tree
- AVL Tree
- AVL Tree
- AVL tree
- AVL tree
- AVL Tree implemention
- AVL Tree Rotation
- AVL Tree 学习笔记
- AVL Tree 的实现
- Root of AVL Tree
- pat 1066(AVL Tree)
- base64计算方法
- 梳理一下重新拿到一个编辑器该做些什么
- HTTP接口跨域-服务端接受返回处理
- 如何查看电脑核数和线程数(网传方法有误)
- 高可用架构-- MySQL主从复制的配置
- Sicily AVL Tree
- JDBC存图片与取出图片
- Android 7.0 行为变更
- Hive中with cube、with rollup、grouping sets用法
- 关于微信二次分享,描述变链接的解决方法(一)----文档说明
- spring事务管理使用总结
- 面试题之数组指针和指针数组的区别
- Springmvc+Apache Camel+Mybatis集成实例及分析
- Android .9.png图片的制作与使用