PAT甲級1066 Root of AVL Tree//平衡二叉樹
技術標籤:# PAT甲級
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
思路
模擬平衡二叉樹的建立,詳細學習樹
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
struct node
{
int val;
int height;
node* left;
node* right;
node(int v) : val(v), height(1), left(NULL), right(NULL) {}
};
int get_height(node* root) { return !root ? 0 : root->height; }
int get_balance_factor(node* root) { return get_height(root->left) - get_height(root->right); }
void update_height(node* root) { root->height = max(get_height(root->left), get_height(root->right)) + 1; }
void LR(node* &root);
void RR(node* &root);
void insert(node* &root, int v);
int main()
{
int n;
cin >> n;
node* root = NULL;
for (int i = 0; i < n; i++)
{
int value;
cin >> value;
insert(root, value);
}
cout << root->val << endl;
system("pause");
return 0;
}
void LR(node* &root)
{
node* temp = root->right;
root->right = temp->left;
temp->left = root;
update_height(root);
update_height(temp);
root = temp;
}
void RR(node* &root)
{
node* temp = root->left;
root->left = temp->right;
temp->right = root;
update_height(root);
update_height(temp);
root = temp;
}
void insert(node* &root, int v)
{
if (!root)
{
root = new node(v);
return;
}
if (v < root->val)
{
insert(root->left, v);
update_height(root);
if (get_balance_factor(root) == 2)
{
if (get_balance_factor(root->left) == 1)
RR(root);
else if (get_balance_factor(root->left) == -1)
{
LR(root->left);
RR(root);
}
}
}
else
{
insert(root->right, v);
update_height(root);
if (get_balance_factor(root) == -2)
{
if (get_balance_factor(root->right) == -1)
LR(root);
else if (get_balance_factor(root->right) == 1)
{
RR(root->right);
LR(root);
}
}
}
}