PAT甲级 A1066
题目详情
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 the root of the resulting AVL tree in one line.
Sample Input 1:
5
88 70 61 96 120
Sample Output 1:
70
Sample Input 2:
7
88 70 61 96 120 90 65
Sample Output 2:
88
解题思路
这道题就是标准的AVL树的建立,并且返回根节点。在本题中需要按序输入此时的输入序列。每次输入时找到需要插入的位置,并在不同的位置搜索此时的二叉树的变化(从递归内部到递归外部),若找到此时的首先出现错误的位置,若该位置为最外层 则更新根节点,否则不进行根节点更新。此时的调整包含LL(1),RR(1),LR(1),RL(1)四种情况。
(1)LL,A节点的左子树的左子树插入错误,此时调整,将左子树调整到A位置,将A调整到左子树的右侧。
(2)RR,A节点的右子树的右子树插入错误,此时调整,将右子树调账到A位置,将A调整到右子树的左侧
(3)LR,A节点的左子树的右子树插入错误,此时先将其左子树执行RR,再对其执行LL
(4)RL,A节点的右子树的左子树插入错误吗,此时先将其右子树执行LL,再对其执行RR
以下为AC代码
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<memory.h>
#include<string>
#include<algorithm>
#include<iomanip>
#include<map>
#include<stack>
#include<queue>;
#include<set>;
#include<iterator>
using namespace std;
class Node {
public:
Node* left = NULL;
Node* right = NULL;
int lhigh=0;
int rhigh=0;
int value;
};
int maxheigh(Node* a) {
if (a == NULL) {
return 0;
}
else {
return max(maxheigh(a->left), maxheigh(a->right))+1;
}
}
Node* LL(Node* &a) {//单次左旋
Node* t1 = a->left;
Node* temp = t1->right;
t1->right = a;
a->left = temp;
return t1;
}
Node* RR(Node*& a) {//单次右旋
Node* t1 = a->right;
Node* temp = t1->left;
t1->left = a;
a->right = temp;
return t1;
}
Node* LR(Node*& a) {//连续左右旋
Node* t1 = a->left;
t1 = RR(t1);
a->left = t1;
return LL(a);
}
Node* RL(Node*& a) {//连续右左旋
Node* t1 = a->right;
t1 = LL(t1);
a->right = t1;
return RR(a);
}
Node* insert(Node* &a,int va) {//需要匹配四种旋转方式
if (a == NULL) {
Node* temp = new Node();
temp->value = va;
a = temp;
return a;
}
else {
if (va > a->value) {
insert(a->right, va);
if (maxheigh(a->right) - maxheigh(a->left) == 2) {
if (va > a->right->value) {
a = RR(a);
}
else {
a = RL(a);
}
}
}
else {
insert(a->left, va);
if ((maxheigh(a->left) - maxheigh(a->right)) == 2) {
if (va < a->left->value) {
a = LL(a);
}
else {
a = LR(a);
}
}
}
}
return a;
}
vector<int> tree;
int main() {
int N; cin >> N;
for (int i = 0; i < N; i++) {
int node;
cin >> node;
tree.push_back(node);
}
Node* root=NULL;
for (int i = 0; i < N ; i++) {
int value = tree[i];
root = insert(root, value);
}
cout << root->value << '\n';
}