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;
}