04-树5 AVL树的根
04-树5 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
谷歌翻译
04-树5 AVL树的根(25分)
AVL树是一种自平衡二进制搜索树。 在AVL树中,任何节点的两个子树的高度最多相差1个。 如果它们之间的任何时间差超过一个,则将进行重新平衡以恢复此属性。 图1-4说明了旋转规则。
现在给出了一系列插入,您应该告诉得到的AVL树的根。
输入规格:
每个输入文件包含一个测试用例。 对于每种情况,第一行都包含一个正整数N(≤20),它是要插入的键的总数。 然后在下一行中给出N个不同的整数键。 一行中的所有数字都用空格分隔。
输出规格:
对于每个测试用例,将结果AVL树的根打印在一行中。
样本输入1:
5
88 70 61 96 120
样本输出1:
70
样本输入2:
7
88 70 61 96 120 90 65
样本输出2:
88
代码
#include <bits/stdc++.h>
using namespace std;
typedef struct Node* Tree;
struct Node{
int data;
Tree left,right;
int height;
};
int height(Tree t){
if(t){
return max(height(t->left),height(t->right))+1;
}else{
return 0;
}
}
//左旋
Tree singleLeft(Tree t){
Tree q=t->left;
t->left=q->right;
q->right=t;
t->height=max(height(t->right),height(t->left));
q->height=max(height(q->right),height(q->left));
return q;
}
//右旋
Tree singleRight(Tree t){
Tree q=t->right;
t->right=q->left;
q->left=t;
q->height=max(height(q->right),height(q->left));
t->height=max(height(t->right),height(t->left));
return q;
}
//左右旋
Tree doubleSingleLeft(Tree t){
t->left=singleRight(t->left);
return singleLeft(t);
}
//右左旋
Tree doubleSingleRight(Tree t){
t->right=singleLeft(t->right);
return singleRight(t);
}
Tree create(Tree t ,int x){
if(t==NULL){
t=(Tree)malloc(sizeof(struct Node));
t->data=x;
t->left=t->right=NULL;
t->height=0;
}else if(x<t->data){
t->left = create(t->left,x);
if(height(t->left)-height(t->right)==2){
if(x<t->left->data){
t=singleLeft(t);
}else{
t=doubleSingleLeft(t);
}
}
}else if(x>t->data){
t->right=create(t->right,x);
if(height(t->right)-height(t->left)==2){
if(x>t->right->data){
t=singleRight(t);
}else{
t=doubleSingleRight(t);
}
}
}
t->height=max(height(t->left),height(t->right));
return t;
}
int main(){
int n;
cin>>n;
Tree t=NULL;
for(int i=1;i<=n;i++){
int x;
cin>>x;
t=create(t,x);
}
cout<<t->data;
return 0;
}