pat 1022(AVL树+完全二叉树)

pat-1123

思路:建立AVL树+判断完全二叉树,AVL树不会出现退化为很长的链表的情况,所以可以给节点编号,

然后通过层序遍历得出编号序列,判断它们是否连续即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
struct Node{
	int data,hi,id;
	struct Node *Left,*Right;
};
typedef struct Node *Tree;
int MAX(int x,int  y)
{
	return x>y?x:y;
}
int Height(Tree T)
{
	if(T==NULL) return -1;
	else return T->hi;
}
Tree LeftRotate(Tree T)
{
	Tree p=T->Left;
	T->Left=p->Right;
	p->Right=T;
	T->hi=MAX(Height(T->Left),Height(T->Right))+1;
	p->hi=MAX(Height(p->Left),T->hi)+1;
	return p;
}
Tree RightRotate(Tree T)
{
	Tree p=T->Right;
	T->Right=p->Left;
	p->Left=T;
	T->hi=MAX(Height(T->Left),Height(T->Right))+1;
	p->hi=MAX(Height(p->Right),T->hi)+1;
	return p;
}
Tree LeftRightRotate(Tree T)
{
	T->Left=RightRotate(T->Left);
	return LeftRotate(T);
}
Tree RightLeftRotate(Tree T)
{
	T->Right=LeftRotate(T->Right);
	return RightRotate(T);
}
Tree Insert(int x,Tree T)
{
	if(T==NULL){
		T=new Node;
		T->data=x;
		T->Left=NULL;
		T->Right=NULL;
		T->hi=0;
	}
	else if(x<T->data){
		T->Left=Insert(x,T->Left);
		if(Height(T->Left)-Height(T->Right)==2){
			if(x<T->Left->data) T=LeftRotate(T);
			else T=LeftRightRotate(T);
		}
	}
	else if(x>T->data){
		T->Right=Insert(x,T->Right);
		if(Height(T->Right)-Height(T->Left)==2){
			if(x>T->Right->data) T=RightRotate(T);
			else T=RightLeftRotate(T);
		}
	}
	T->hi=MAX(Height(T->Left),Height(T->Right))+1;
	return T;
}
vector <int> ans,vc;
void bfs(Tree T)
{
	Tree tmp;
	T->id=1;
	ans.clear();
	vc.clear();
	queue <Tree> q;
	q.push(T);
	while(!q.empty()){
		tmp=q.front();q.pop();
		ans.push_back(tmp->data);
		vc.push_back(tmp->id);
		if(tmp->Left!=NULL){
			tmp->Left->id=tmp->id*2;
			q.push(tmp->Left);
		}
		if(tmp->Right!=NULL){
			tmp->Right->id=tmp->id*2+1;
			q.push(tmp->Right);
		}
	}
}
int main(void)
{
	int n,i,x;
	Tree T=NULL;
	cin>>n;
	for(i=0;i<n;i++){
		cin>>x;
		T=Insert(x,T);
	}
	bfs(T);
	int fg=0;
	for(i=0,x=ans.size();i<x;i++){
		if(i){
			cout<<" ";
			if(vc[i]-vc[i-1]!=1) fg=1;
		}
		cout<<ans[i];
	}
	cout<<endl;
	if(fg==0) cout<<"YES"<<endl;
	else cout<<"NO"<<endl;
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值