AVL_insert_1066 Root of AVL Tree (25 分)
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_tree樹的操作,可以參見另外一篇部落格:c++實現AVL_tree
AVL樹的插入操作還是較為簡單的,只有四種情況需要考慮,需要在插入的過程中不斷進行更新,每當發現當前節點不滿足平衡條件時,執行對應的平衡調整操作
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 25;
struct Node
{
int val,height;
struct Node *left;
struct Node *right;
};
int height(Node *node)
{
if(node != NULL)
return node->height;
return 0;
}
Node* AVL_LL(Node *node)
{
Node *temp = node->left;
node->left = temp->right;
temp->right = node;
node->height = max(height(node->left),height(node->right)) + 1;
temp->height = max(height(temp->left),height(temp->right)) + 1;
return temp;
}
Node* AVL_RR(Node *node)
{
Node *temp = node->right;
node->right = temp->left;
temp->left = node;
node->height = max(height(node->left),height(node->right)) + 1;
temp->height = max(height(temp->left),height(temp->right)) + 1;
return temp;
}
Node *AVL_LR(Node *node)
{
node->left = AVL_RR(node->left);
return AVL_LL(node);
}
Node *AVL_RL(Node *node)
{
node->right = AVL_LL(node->right);
return AVL_RR(node);
}
Node* AVL_insert(Node *&node,int val)
{
if(node == NULL)
{
node = new Node;
node->val = val;node->right = NULL;node->left = NULL;
}
else if(node->val > val)
{
node->left = AVL_insert(node->left,val);
if(height(node->left) - height(node->right) == 2)
{
if(val > node->left->val)
node = AVL_LR(node);
else
node = AVL_LL(node);
}
}
else if(node->val < val)
{
node->right = AVL_insert(node->right,val);
if(height(node->right) - height(node->left) == 2)
{
if(val > node->right->val)
node = AVL_RR(node);
else
node = AVL_RL(node);
}
}
node->height = max(height(node->left),height(node->right)) + 1;
return node;
}
int main()
{
Node *root = NULL;
int n,x;
scanf("%d",&n);
for(int i = 0;i < n;i ++)
{
scanf("%d",&x);
AVL_insert(root,x);
}
printf("%d\n",root->val);
return 0;
}