PAT (Advanced Level) Practice 1123 Is It a Complete AVL Tree (30分)

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值