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
8 10 11 8 6 7 5
Sample Output 2:
88
分析:
1、左旋(右子树过高):
补充:结点3是忍痛割爱,将自己的左子树砍断,而将紫色集团植入。
2、右旋(左子树过高):正好和左旋相反,此处不详述。
3、右左旋(往左子树的右子树上插入了新结点):先右旋,再左旋
4、左右旋(往右子树的左子树上插入了新结点):先左旋,再右旋,正好和右左旋相反,此处不详述。
代码如下
#include<iostream>
#include<cmath>
using namespace std;
struct node{
int val;
struct node *left,*right;
};
node *L(node *root)
{
node *temp = root->right;
root->right = temp->left;
temp->left = root;
return temp;
}
node *R(node *root)
{
node *temp = root->left;
root->left = temp->right;
temp->right = root;
return temp;
}
node *RL(node *root)
{
root->right = R(root->right);
return L(root);
}
node *LR(node *root)
{
root->left = L(root->left);
return R(root);
}
int height(node *root)
{
if(root == NULL) return 0;
return max(height(root->left),height(root->right))+1;
}
node *insert(node *root,int val)
{
if(root == NULL){
root = new node();
root->val = val;
root->left = root->right = NULL;
}else if(val < root->val){
root->left = insert(root->left, val);
if(height(root->left)-height(root->right)==2)
root = val<root->left->val?R(root):LR(root);
}else{
root->right = insert(root->right, val);
if(height(root->right)-height(root->left)==2)
root = val>root->right->val?L(root):RL(root);
}
return root;
}
int main()
{
int n,val;
cin>>n;
node *root = NULL;
for(int i = 0; i < n; i++){
cin>>val;
root = insert(root, val);
}
cout<<root->val;
return 0;
}