【2019暑期】【PAT甲级】1110 Complete Binary Tree (25 分)

48 篇文章 0 订阅

复习了dfs的写法
用队列和循环,判断标准是队列是否有内容

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;

int n;
int head[30];
struct node{
	int left,right;
};

int main()
{
 	
 	cin >> n;
 	memset(head,-1,sizeof(head));
 	vector<node> ans(n);
 	for(int i=0; i<n; i++){
 		string a,b;
 		cin >> a >> b;
 		if(a != "-"){
 			ans[i].left = stoi(a);
 			head[stoi(a)] = i;
		 } 			
 		else ans[i].left = -1;
 		if(b!= "-"){
 			ans[i].right = stoi(b);
 			head[stoi(b)] = i;
		 }
 		else ans[i].right = -1;
	}
	int root;
 	for(int i=0; i<n; i++){
 		if(head[i]==-1){
 			root = i;
 			break;
		 }
	 }
	 queue<int> q;
	 q.push(root);
	 int cnt=0,last;
	 while(!q.empty()){
	 	int temp = q.front();
	 	q.pop();
	 	if(temp != -1){
	 		cnt++;
			last = temp;	 		
		 }
		 else{
		 	if(cnt!=n) cout << "NO " << root << endl;
			else cout << "YES " << last << endl;
			break;
		 }
		 q.push(ans[temp].left);
		 q.push(ans[temp].right);
	 } 
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值