A1110 Complete Binary Tree (25) DFS,逻辑题,完全二叉树的一般判别方法

做本题的时候先考虑用层序,但是没有思绪,又转为考虑DFS的解法,pat的很多解法是双重标注的方法,在做题的时候需要认真想明白index和root分别指向的是当前的位置和当前的元素,两者通过元素访问,index通过访问变化。本题是DFS解法,但是和前面的逻辑题本质无差别。
本题的另外一个需要注意的事项是,因为访问元素可能超过10,这时不能再用char来接受了。
DFS解法

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=25;
int maxnum=-1,finalnode;
struct node
{
	int lchild,rchild;
}a[maxn];
bool hashtable[maxn]={false};
int charTonum(string x)
{
	if(x=="-")
	return -1;
	else
	{
		int num=stoi(x);
		hashtable[num]=true;
		return num;
	}
}
void DFS(int root,int index)
{
	
	if(index>maxnum) 
	{
		maxnum=index;
		finalnode=root;
	}
	if(a[root].lchild!=-1)DFS(a[root].lchild,index*2);
	if(a[root].rchild!=-1)DFS(a[root].rchild,index*2+1);
}
int main()
{
	int n,root;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		string  c1,c2;
		cin>>c1>>c2;
		a[i].lchild=charTonum(c1);
		a[i].rchild=charTonum(c2);
	}
	for(int i=0;i<n;i++)
	{
		if(hashtable[i]==false)
		{
			root=i;
			break;
		}
	}
	DFS(root,1);
	if(maxnum>n)
	printf("NO %d",root);
	else
	{
		printf("YES %d",finalnode);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值