PAT 1110. Complete Binary Tree (25) 完全二叉树判断

/*************************
题意:
判断所给树是否是完全二叉树
************************/
/***********************
解题思路:
先建立树
建立之后,
把该树按数组树的形式存入数组中(左儿子是i*2,右儿子是i*2+1,根节点是1)
存完之后,检索一下,看看该数组是否是满的,
如果有空缺,说明不是完全二叉树
*************************/
/***********************
笔记:
有一个地方卡了一下:
	就是我试着用char读入L和R,然后判断是否等于‘-’
	却忘记了可能会输出2位数字的情况,所以不能用char
*********************/
#include<iostream>
#include<stdio.h>
#include<string>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<map>
#include<set>
#include<unordered_map>
using namespace std;
#define M 10005
#define INF 0x7ffffff
int Left[M],Right[M];
int num[M];
void gettree(int root,int i){
	if(root == -1)
		return ;
	num[i] = root;
	gettree(Left[root],i*2);
	gettree(Right[root],i*2+1);
}


int main(){
	int n , m, i;
	int L, R;

	int rootflag[150];
	memset(rootflag,0,sizeof(rootflag));
	cin>>n;
	for(i = 1;i <= n;i++)
		num[i] = -1;


	string SL,SR;
	for(i = 0;i < n; i++){
		cin>>SL>>SR;
		if(SL[0] == '-')
			Left[i] = -1;
		else{
			L = atoi(SL.c_str());
			Left[i] = L ;
			rootflag[L] = 1;
		}
		
		if(SR[0] == '-')
			Right[i] = -1;
		else{
			R = atoi(SR.c_str());
			Right[i] = R ;
			rootflag[R] = 1;
		}
	}
	int root;
	for(i = 0;i<n;i++)
		if(rootflag[i] == 0)
			root = i;
	
	int f;
	gettree(root, 1);
	for(i = 1;i <= n;i++)
		if(num[i] == -1)
			break;


	if(i == n+1){
		printf("YES %d\n",num[n]);
	}
	else{
		printf("NO %d\n",root);
	}


	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值