1066 Root of AVL Tree 25 ☆☆☆
github地址:https://github.com/iofu728/PAT-A-by-iofu728
难度:☆☆☆
关键词:二叉平衡树,AVL
题目
1066.Root of AVL Tree (25)
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
(<=20) 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 ythe root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120Sample Output 1:
70Sample Input 2:
7
88 70 61 96 120 90 65Sample Output 2:
88
大意
给出二叉平衡树AVL
的插入顺序,输出最后树的根节点值。
思路
- 很久没做二叉树的题目了,特意来回顾一下。
- 二叉树建树很套路的分为
newNode
,insert
,create
三个函数。 - 如果是二叉查找树
BST
,需要对insert
分类一下,总体和普通树一致。 - 特殊的是二叉平衡树
AVL
- 一要更新树高,增加
getheight
,geibanlance
,update
三个函数。 - 二是要对不平衡情况的修正。
若getbanlance==2,左子树getbanlance==1,R;左子树==-1,LR。
若getbanlance==-2,右子树getbanlance==-1,L;右子树==1,RL。
L
,R
分别为向左、右转。
code
#include <algorithm>
#include <iostream>
using namespace std;
struct node {
int data, height;
node *left, *right;
};
node *newNode(int num) {
node *root = new node;
root->data = num;
root->height = 1;
root->left = root->right = NULL;
return root;
}
int getheight(node *root) {
if (root == NULL) return 0;
return root->height;
}
int getbalance(node *root) {
return getheight(root->left) - getheight(root->right);
}
int update(node *&root) {
root->height = max(getheight(root->left), getheight(root->right)) + 1;
}
void L(node *&root) {
node *temp = root->right;
root->right = temp->left;
temp->left = root;
update(root);
update(temp);
root = temp;
}
void R(node *&root) {
node *temp = root->left;
root->left = temp->right;
temp->right = root;
update(root);
update(temp);
root = temp;
}
node insert(node *&root, int num) {
if (root == NULL) {
root = newNode(num);
} else if (root->data > num) {
insert(root->left, num);
update(root);
if (getbalance(root) == 2) {
if (getbalance(root->left) == 1) {
R(root);
} else if (getbalance(root->left) == -1) {
L(root->left);
R(root);
}
}
} else {
insert(root->right, num);
update(root);
if (getbalance(root) == -2) {
if (getbalance(root->right) == -1) {
L(root);
} else if (getbalance(root->right) == 1) {
R(root->right);
L(root);
}
}
}
}
node *create(int n) {
int num;
node *root = NULL;
for (int i = 0; i < n; ++i) {
scanf("%d", &num);
insert(root, num);
}
return root;
}
int main() {
int n;
scanf("%d", &n);
node *root = create(n);
printf("%d\n", root->data);
return 0;
}