PTA平衡二叉树的根(25分)
将给定的一系列数字插入初始为空的AVL树,请你输出最后生成的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
此题考查的即是平衡二叉树的创建。
AC代码:
#include<iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
struct node{
int data;
int high;
struct node *lt, *rt;
};
int max(int a,int b){
return a>b?a:b;
}
int deep(struct node *root){
if(root==NULL)return -1;
else return root->high;
}
struct node *LL(struct node *root){
struct node *p=root->lt;
root->lt=p->rt;
p->rt=root;
root->high=max(deep(root->lt), deep(root->rt))+1;
return p;
}
struct node *RR(struct node *root){
struct node *p=root->rt;
root->rt=p->lt;
p->lt=root;
root->high=max(deep(root->lt), deep(root->rt))+1;
return p;
}
struct node *RL(struct node *root){
root->rt=LL(root->rt);
root=RR(root);
return root;
}
struct node *LR(struct node *root){
root->lt=RR(root->lt);
root=LL(root);
return root;
}
struct node *Insert(struct node *root, int num){
if(!root){
root=(struct node *)malloc(sizeof(struct node));
root->data=num;
root->high=0;
root->lt=NULL;
root->rt=NULL;
}
else{
if(num<root->data){///数据比根小
root->lt=Insert(root->lt, num);///加到左子树上
///先判断是否要转
if(abs(deep(root->lt)-deep(root->rt))>1){//深度之差大于一就转
if(num>=root->lt->data){///比左子根大,转两次,即LR
root=LR(root);
}
else{///比左子根小,转一次,即LL
root=LL(root);
}
}
}
else{///比根大
root->rt=Insert(root->rt, num);///加到右子树上
if(abs(deep(root->lt)-deep(root->rt))>1){
if(num>=root->rt->data){///加到右子树的右边,转一次,RR
root=RR(root);
}
else{///加到右子树的左边,转两次,RL
root=RL(root);
}
}
}
}
root->high=max(deep(root->lt), deep(root->rt))+1;
return root;
}
int main(void){
struct node *root=NULL;
int n, num;
scanf("%d", &n);
while(n--){
scanf("%d", &num);
root=Insert(root, num);
}
printf("%d\n", root->data);
return 0;
}