博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT甲级——A1066 Root of AVL Tree
阅读量:4541 次
发布时间:2019-06-08

本文共 2564 字,大约阅读时间需要 8 分钟。

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

 

 

 

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

 

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

588 70 61 96 120

Sample Output 1:

70

Sample Input 2:

788 70 61 96 120 90 65

Sample Output 2:

88
1 #include 
2 using namespace std; 3 struct node { 4 int val; 5 struct node *left, *right; 6 }; 7 node *rotateLeft(node *root) { 8 node *t = root->right; 9 root->right = t->left;10 t->left = root;11 return t;12 }13 node *rotateRight(node *root) {14 node *t = root->left;15 root->left = t->right;16 t->right = root;17 return t;18 }19 node *rotateLeftRight(node *root) {20 root->left = rotateLeft(root->left);21 return rotateRight(root);22 }23 node *rotateRightLeft(node *root) {24 root->right = rotateRight(root->right);25 return rotateLeft(root);26 }27 int getHeight(node *root) {28 if(root == NULL) return 0;29 return max(getHeight(root->left), getHeight(root->right)) + 1;30 }31 node *insert(node *root, int val) {32 if(root == NULL) {33 root = new node();34 root->val = val;35 root->left = root->right = NULL;36 } else if(val < root->val) {37 root->left = insert(root->left, val);38 if(getHeight(root->left) - getHeight(root->right) == 2)39 root = val < root->left->val ? rotateRight(root) : rotateLeftRight(root);40 } else {41 root->right = insert(root->right, val);42 if(getHeight(root->left) - getHeight(root->right) == -2)43 root = val > root->right->val ? rotateLeft(root) : rotateRightLeft(root);44 }45 return root;46 }47 int main() {48 int n, val;49 scanf("%d", &n);50 node *root = NULL;51 for(int i = 0; i < n; i++) {52 scanf("%d", &val);53 root = insert(root, val);54 }55 printf("%d", root->val);56 return 0;57 }

 

转载于:https://www.cnblogs.com/zzw1024/p/11306122.html

你可能感兴趣的文章
Android——四大组件、六大布局、五大存储
查看>>
Socket实现原理和机制
查看>>
luogu1265 公路修建
查看>>
WORD2003电子签名插件(支持手写、签章)
查看>>
Google开源项目二维码读取与生成工具ZXing
查看>>
Android使用默认样式创建View的几个姿势
查看>>
多标记学习--Learning from Multi-Label Data
查看>>
leetcode 47. 全排列 II
查看>>
1083 List Grades (25)
查看>>
使用iptables和tc对端口限速
查看>>
14、反射(reflect)
查看>>
树-哈夫曼树
查看>>
异步复位同步释放
查看>>
【Spark2.0源码学习】-7.Driver与DriverRunner
查看>>
poj 1206
查看>>
Spring基础系列-参数校验
查看>>
php+ajax实现图片文件上传功能
查看>>
SQL日期格式化及创建相关日期
查看>>
模式识别--概率密度
查看>>
linux 安装虚拟机
查看>>