PAT (Advanced Level) Practice Complete Binary Tree

本题运用到了树的静态写法来创建树,二叉树的层序遍历来检验该二叉树是否为完全二叉树

题目

在层序遍历中,如果遇到结点为空的情况(在代码中表示为-1)的情况,则说明该树不是一棵完全二叉树,,则输出 No和根节点;如果遍历了全部的结点(均不为空),则输出Yes和最后一个结点

这是我之前刷 PTA(Advanced Level) 其他有关树的题目,从《算法笔记上机训练实战指南》中学习到如何获取根节点的方法,在这里提一下

获得二叉树的根节点编号,即0~(N-1)中未在输入中出现过的那个数。

代码如下

#include <cstdio>
#include <queue>
using namespace std;
const int maxn=22;
bool vis[maxn]={false};
int n, last, ans=0;
bool flag=true;
struct node{
	int lchild, rchild;
}no[maxn];

void bfs(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int front=q.front();
		q.pop();
		
		if(front==-1){
			flag=false;
			break;
		}
	
		if(ans==(n-1)){
			last=front;
			break;
		}
		
		ans+=1;     
		q.push(no[front].lchild);
		q.push(no[front].rchild);
	}
}

int main()
{
    scanf("%d", &n);
    getchar();
	for(int i=0; i<n; i++){
		int x=0;
		char temp=getchar();
		while(temp!=' '){
			if(temp=='-'){
				x=-1;
			} else {
				x=x*10+(temp-'0');
			}
			    
			temp=getchar();
		}
		
		no[i].lchild=x;
		if(x!=-1)
		   vis[x]=true;
		   
		temp=getchar();
		x=0;
		while(temp!='\n'){
			if(temp=='-'){
				x=-1;
			} else {
				x=x*10+(temp-'0');
			}
			    
			temp=getchar();
		} 
		
		no[i].rchild=x;
		if(x!=-1)
		    vis[x]=true;
	}	
	
	int root;
	for(int i=0; i<n; i++){
		if(!vis[i]){
			root=i;
			break;
		}
	}
	
	bfs(root);
	if(flag)
	    printf("YES %d\n", last);
	else
	    printf("NO %d\n", root);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值