题目:
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树的操作,没有多大的难度。要注意递归的正确的调用还有指针的运用,还有一些小的细节自己也不能粗心大意。
代码:
#include<iostream>
using namespace std;
typedef struct TreeNode *Tree;
struct TreeNode{
int Key;//存储节点要保存的信息
Tree Left, Right;
int Height;//表示数高
};
int Height(Tree T){
if (T == NULL){ return -1; }
else { return T->Height; }
}
int MaxHeight(int a, int b){//返回子树中较大的一个树高
return a > b ? a : b;
}
Tree LLrotation(Tree T1){//左左旋转
Tree T2;
T2 = T1->Left;
T1->Left = T2->Right;
T2->Right = T1;//完成旋转
T1->Height = MaxHeight(Height(T1->Left), Height(T1->Right)) + 1;
T2->Height = MaxHeight(Height(T2->Left), Height(T1)) + 1;
return T2;
}
Tree RRrotation(Tree T1){//右右旋转
Tree T2;
T2 = T1->Right;
T1->Right = T2->Left;
T2->Left = T1;
T1->Height = MaxHeight(Height(T1->Left), Height(T1->Right)) + 1;
T2->Height = MaxHeight(Height(T1), Height(T2->Right)) + 1;
return T2;
}
Tree LRrotation(Tree T1){//左右旋转
T1->Left = RRrotation(T1->Left);
return LLrotation(T1);
}
Tree RLrotation(Tree T1){//右左旋转
T1->Right = LLrotation(T1->Right);
return RRrotation(T1);
}
Tree Insert(Tree T, int key){
if (!T) {//节点为空
T =new TreeNode;
T->Key = key;
T->Left = T->Right = NULL;
T->Height = 0;
}
else{//节点不为空
if (key < T->Key){//往该节点的左子树插入
T->Left = Insert(T->Left, key);
if (Height(T->Left) - Height(T->Right) == 2){//左子树较高
if (key < T->Left->Key){
T = LLrotation(T);
}
else{
T = LRrotation(T);
}
}
}
else{//往该节点的右子树插入
T->Right = Insert(T->Right, key);
if (Height(T->Right) - Height(T->Left) == 2){//右子树较高
if (key>T->Right->Key){
T = RRrotation(T); }
else {
T = RLrotation(T); }
}
}
}
T->Height = MaxHeight(Height(T->Left), Height(T->Right)) + 1;
return T;
}
Tree MakeTree(int N){//创建一颗树
int key;
Tree T;
T = new TreeNode;
cin >> key;
T->Key = key;
T->Left = T->Right = NULL;
T->Height = 0;
for (int i = 1; i < N; i++){
cin >> key;
T = Insert(T, key);
}
return T;
}
int main(){
int N;
Tree T;
cin >> N;
T = MakeTree(N);
cout << T->Key;
}