1159 Structure of a Binary Tree

文章讲述了如何使用递归方法构建二叉树,并通过后序遍历和中序遍历来维护节点信息。同时,定义了检查函数来验证树的特定属性如父节点、深度和满树条件。
摘要由CSDN通过智能技术生成

技巧

先建立树,然后在建树的过程中
1.维护当前的深度
2.保存每个点的父节点
3.判断当前的点是否是全空或者全满,不是的话说明当前不是一个满树

AC

#include <bits/stdc++.h>
//#define int long long
#define eb emplace_back
#define pii  pair<int,int>
#define endl "\n"
using namespace std;
using ll=long long;
const ll mod=1e9+7;
const int N=1e3+10;
int k,n,m;
struct node
{
	int ls,rt,pa,level;
	node()
	{
		ls=rt=pa=-1;
	}
}nds[N];
int postorder[N],inorder[N];
int root,full=1;
int build(int h1,int h2,int l,int pa)
{
	if(l<=0)return -1;
	int cur=postorder[h1];//当前所在的节点的值 
	int i;
	for(i=h2;;++i)if(postorder[h1]==inorder[i])break;
	int l1=i-h2;
	int l2=l-l1-1;
	nds[cur].pa=pa;
	nds[cur].level=nds[pa].level+1;
	nds[cur].ls=build(h1-1-l2,h2,l1,cur);
	nds[cur].rt=build(h1-1,i+1,l2,cur);
	if(nds[cur].ls*nds[cur].rt<0)full=0;
	return cur;
}

bool check()
{
	string tmp;
	string a,b,c,d;
	cin>>a>>b>>c>>d;
//	cout<<a<<" "<<b<<" "<<c<<" "<<d<<"==\n";
	if(d=="are")
	{
		cin>>tmp;
		if(tmp=="siblings")
		{
			int zhi1=stoi(a),zhi2=stoi(c);
			if(nds[zhi1].pa==nds[zhi2].pa)return 1;
			else return 0;
		}
		else
		{
			cin>>tmp;cin>>tmp;cin>>tmp;
			int zhi1=stoi(a),zhi2=stoi(c);
			if(nds[zhi1].level==nds[zhi2].level)return 1;
			else return 0;
		}
	}
	else if(d=="root")
	{
		int zhi1=stoi(a);
		if(zhi1==root)return 1;
		else return 0;
	}
	else if(d=="parent")
	{
		cin>>b;cin>>b;
		int zhi1=stoi(a),zhi2=stoi(b);
		if(nds[zhi2].pa==zhi1)return 1;
		else return 0;
	}
	else if(d=="left")
	{
		cin>>b;cin>>b;cin>>b;
		int zhi1=stoi(a),zhi2=stoi(b);
		if(nds[zhi2].ls==zhi1)return 1;
		else return 0;
	}
	else if(d=="right")
	{
		cin>>b;cin>>b;cin>>b;
		int zhi1=stoi(a),zhi2=stoi(b);	
		if(nds[zhi2].rt==zhi1)return 1;
		else return 0;	
	}
	else if(d=="full")
	{
		cin>>tmp;
		if(full)return 1;
		else return 0;
	}
}

void solve()
{
	cin>>n;
	for(int i=0;i<n;++i)cin>>postorder[i];
	for(int i=0;i<n;++i)cin>>inorder[i];
	root=build(n-1,0,n,1010);
//	cout<<root->data;
	cin>>m;
	while(m--)
	{
		if(check())cout<<"Yes\n";
		else cout<<"No\n";
	}
} 

int main()
//signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int T=1;
	while(T--)
	{
		solve(); 
	}
	return 0;
}
/*
*/

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值