#include<cstdio>
#include<algorithm>
#include<stdlib.h>
#include<queue>
const int maxn = 2020;
using namespace std;
struct node{
struct node*left;
struct node*right;
int height;
int data;
};
typedef struct node*AVLTree;
int n;
int data[maxn],in[2020];
int index = 0;
int space = 0;
void inorder(int root)
{
if(root>n) return;
inorder(2*root);
in[root] = data[index++];
inorder(2*root+1);
}
void levelorder(AVLTree T,int *a)
{
queue<AVLTree>qu;
qu.push(T);
AVLTree node;
int k = 1;
while(qu.empty()!=true){
node = qu.front();
qu.pop();
if(space) printf(" ");
printf("%d",node->data);
if(node->data!=in[k++]){
*a = 1;
}
space = 1;
if(node->left) qu.push(node->left);
if(node->right) qu.push(node->right);
}
}
int getheight(AVLTree T)
{
if(T==NULL) return 0;
return T->height;
}
void updateheight(AVLTree A)
{
A->height = max(getheight(A->left),getheight(A->right))+1;
}
AVLTree LL(AVLTree A)
{
AVLTree B = A->left;
A->left = B->right;
B->right = A;
updateheight(A);
updateheight(B);
return B;
}
AVLTree RR(AVLTree A)
{
AVLTree B = A->right;
A->right = B->left;
B->left = A;
updateheight(A);
updateheight(B);
return B;
}
AVLTree LR(AVLTree A)
{
A->left = RR(A->left);
return LL(A);
}
AVLTree RL(AVLTree A)
{
A->right = LL(A->right);
return RR(A);
}
AVLTree insert(AVLTree T,int X)
{
if(!T){
T=(AVLTree)malloc(sizeof(struct node));
T->height = 1;
T->data = X;
T->left=T->right = NULL;
}else if(X < T->data){
T->left = insert(T->left,X);
if(getheight(T->left) - getheight(T->right)==2){
if(X<T->left->data){
T = LL(T);
}else{
T = LR(T);
}
}
}else if(X>T->data){
T->right = insert(T->right,X);
if(getheight(T->left) - getheight(T->right)==-2){
if(X>T->right->data){
T = RR(T);
}else{
T = RL(T);
}
}
}
updateheight(T);
return T;
}
int main()
{
int count = 0;
AVLTree A = NULL;
int x;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&x);
data[i] = x;
A = insert(A,x);
}
sort(data,data+n);
inorder(1);
levelorder(A,&count);
printf("\n");
if(count) printf("NO");
else printf("YES");
return 0;
}
PAT (Advanced Level) Practice 1123 Is It a Complete AVL Tree (30分)
最新推荐文章于 2021-04-05 12:36:35 发布