PAT甲级1135

做出来了,但感觉心好痛。我发现我真是太懒惰了,以为简简单单记个模板,就万事大吉了。

没想到自己的思维被模板固化,就不会根据实际情况作出相应的改变了。模板当然要记忆,

但不可偷懒而导致思维僵化。引以为戒

dfs为判断过程,是在求树高的基础上,增加一个参数,判断是否存在前一个为红色节点并且当前节点是红色的情况

回溯判断当前节点的左右子树的黑高是否相等

#include<cstdio>
#include<algorithm>
#include<cmath>
//#define debug
using namespace std;
const int maxn=40;
struct node{
	int data;
	int lc;
	int rc;
	node(){
		data=0;
		lc=rc=-1;
	}
};
bool cmp(int a,int b)
{
	return abs(a)<abs(b);
}
int n;
int ptr=0;
node Tree[maxn];
int pre[maxn];
int in[maxn];
void create(int &root,int preL,int preR,int inL,int inR)
{
	if(preL>preR)return;
	if(preL>=n)return;
	int roote=pre[preL];
	root=ptr++;
	Tree[root].data=roote;
	int u=0;
	for(u=inL;u<=inR;u++){
		if(in[u]==roote)break;
	}
	int numLeft=u-inL;
	create(Tree[root].lc,preL+1,preL+numLeft,inL,u-1);
	create(Tree[root].rc,preL+numLeft+1,preR,u+1,inR);
}
bool IsRBt=true;
int dfs(int root,int pren)
{
	if(IsRBt==false)return -1;
	if(root==-1)return 1;
	if(pren<0&&Tree[root].data<0){
		IsRBt=false;
		return -1;
	}
	int lh=dfs(Tree[root].lc,Tree[root].data);
	int rh=dfs(Tree[root].rc,Tree[root].data);
	if(rh!=lh){
		IsRBt=false;
		return -1;
	}
	return Tree[root].data>0?max(lh,rh)+1:max(lh,rh);
}
int main()
{
#ifdef debug
	freopen("in.txt","r",stdin);
#endif
	int t;
	node s;
	scanf("%d",&t);
	for(int i=0;i<t;i++){
		scanf("%d",&n);
		fill(Tree,Tree+maxn,s);
		ptr=0;
		IsRBt=true;
		for(int i=0;i<n;i++){
			scanf("%d",&pre[i]);
			in[i]=pre[i];
		}
		sort(in,in+n,cmp);
		int root;
		create(root,0,n-1,0,n-1);
		if(Tree[root].data<0)IsRBt=false;
		else
			dfs(root,Tree[root].data);
		if(IsRBt)printf("Yes\n");
		else printf("No\n");
	}
#ifdef debug
	getchar();
#endif
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值