1066 Root of AVL Tree (25point(s))
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 代碼,沒有其他要求
編譯器:C (gcc)
#include <stdio.h>
#include <stdlib.h>
struct node {
int d;
struct node *left, *right;
};
int max(int a, int b)
{
return a > b ? a : b;
}
int get_height(struct node *root)
{
if (root == NULL)
return 0;
return max(get_height(root->left), get_height(root->right)) + 1;
}
struct node *left_rotate(struct node *root)
{
struct node *t = root->right;
root->right = t->left;
t->left = root;
return t;
}
struct node *right_rotate(struct node *root)
{
struct node *t = root->left;
root->left = t->right;
t->right = root;
return t;
}
struct node *right_left_rotate(struct node *root)
{
root->right = right_rotate(root->right);
return left_rotate(root);
}
struct node *left_right_rotate(struct node *root)
{
root->left = left_rotate(root->left);
return right_rotate(root);
}
struct node *insert(struct node *root, int d)
{
if (root == NULL) {
root = (struct node *)malloc(sizeof(struct node));
root->d = d;
root->left = NULL;
root->right = NULL;
} else if (d < root->d) {
root->left = insert(root->left, d);
if (get_height(root->left) - get_height(root->right) == 2)
root = d < root->left->d ? right_rotate(root) : left_right_rotate(root);
} else {
root->right = insert(root->right, d);
if (get_height(root->left) - get_height(root->right) == -2)
root = d > root->right->d ? left_rotate(root) : right_left_rotate(root);
}
return root;
}
int main(void)
{
int n;
int i, t;
struct node *root = NULL;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &t);
root = insert(root, t);
}
printf("%d", root->d);
return 0;
}