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.
#include <iostream>
#include <algorithm>
using namespace std;
typedef struct AVLNode* AVLTree;
struct AVLNode{
int data; //结点的值
AVLTree left; //左儿子
AVLTree right; //右儿子
int height; //结点的高度
};
//获得树的高度
int getHeight(AVLTree a){
return a == nullptr ? -1 : a->height;
}
//LL单旋 把b的右子树腾出来挂给A的左子树,再将a挂到b的右子树上去
AVLTree LLRotation(AVLTree a){
//此时根结点是a
AVLTree b = a->left; //b为a的左子树
a->left = b->right; //b的右子树挂在a的左子树上
b->right = a; //a挂在b的右子树上
a->height = max(getHeight(a->left), getHeight(a->right)) + 1;
b->height = max(getHeight(b->left), a->height) + 1;
return b; //此时根结点为b
}
//RR单旋
AVLTree RRRotation(AVLTree a){
AVLTree b = a->right;
a->right = b->left;
b->left = a;
a->height = max(getHeight(a->left), getHeight(a->right)) + 1;
b->height = max(getHeight(b->right), a->height) + 1;
return b;
}
//LR双旋
AVLTree LRRotation(AVLTree a){
//先RR单旋
a->left = RRRotation(a->left);
//再LL单旋
return LLRotation(a);
}
//RL双旋
AVLTree RLRotation(AVLTree a){
//先LL单旋
a->right = LLRotation(a->right);
//再RR单旋
return RRRotation(a);
}
AVLTree Insert(AVLTree t, int x){
if(!t){ //结点为空
t = (AVLTree)malloc(sizeof(struct AVLNode));
t->data = x;
t->left = t->right = nullptr;
t->height = 0;
}else{
if(x < t->data){
t->left = Insert(t->left, x);
if(getHeight(t->left) - getHeight(t->right) == 2) {
if(x < t->left->data) //LL单旋
t = LLRotation(t);
else if(t->left->data < x) //LR双旋
t = LRRotation(t);
}
}else if(t->data < x){
t->right = Insert(t->right, x);
if(getHeight(t->right) - getHeight(t->left) == 2){
if(x < t->right->data) //RL双旋
t = RLRotation(t);
else if(t->right->data < x) //RR单旋
t = RRRotation(t);
}
}
}
//更新树高
t->height = max(getHeight(t->left), getHeight(t->right)) + 1;
return t;
}
int main()
{
AVLTree t = nullptr;
int n;
cin >> n;
for(int i = 0; i < n; i++){
int tmp;
cin >> tmp;
t = Insert(t, tmp);
}
cout << t->data;
return 0;
}
这篇博客介绍了AVL树的基本概念,它是一种自我平衡的二叉搜索树。文章详细阐述了AVL树的特性,即任意节点的两个子树高度差不超过1,并通过4种旋转规则(LL单旋、RR单旋、LR双旋和RL双旋)来保持平衡。接着,给出了C++代码实现AVL树的插入操作,包括插入节点后的高度计算和四种旋转方法。最后,提供了一个主函数示例,展示如何对一系列插入操作后的AVL树的根节点进行输出。
1115

被折叠的 条评论
为什么被折叠?



