PTA列出叶结点(BFS)

对于给定的二叉树,本题要求你按从上到下、从左到右的顺序输出其所有叶节点。

输入格式:

首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 “-”。编号间以 1 个空格分隔。

输出格式:

在一行中按规定顺序输出叶节点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

输出样例:

4 1 5

实现:
题意理解了半天… 开个标记数组,在叶子左右孩子节点中出现过的就进行标记。剩下的那一个就是root,然后在进行BFS

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<list>
#include<set>
#include<cmath>
using namespace std;
typedef long long ll;

struct node{
	int leaf ;
	int right;
}q[15]; 
queue<int> qu; 
int res[15],top=0;
void bfs(){
	while(qu.size()){
		int num = qu.front();
		qu.pop();
		if(q[num].leaf==-1&&q[num].right==-1) res[top++] = num;
		if(q[num].leaf!=-1) qu.push(q[num].leaf);
		if(q[num].right!=-1) qu.push(q[num].right);
		
	}
}
int main(){
	int n,root;
	cin >> n;
	getchar();
	int flag[n];
	char a,b;
	memset(q,0,sizeof(q));
	memset(flag,0,sizeof(flag));
	for(int i=0;i<n;i++){
		scanf("%c %c",&a,&b);
		getchar();
		if(a=='-') q[i].leaf=-1;
		else {
			q[i].leaf = a-'0';flag[q[i].leaf] = 1;
		} 
		if(b=='-') q[i].right=-1;
		else {
			q[i].right = b-'0';flag[q[i].right] = 1;
		} 	
	}
	for(int i=0;i<n;i++){
		if(flag[i]==0){
			root = i;
			break;
		}
	}
	qu.push(root);
	bfs();
	cout << res[0];
	for(int i=1;i<top;i++){
		cout << " " << res[i];
	}
	return 0;
}
发布了63 篇原创文章 · 获赞 34 · 访问量 6551

猜你喜欢

转载自blog.csdn.net/SinclairWang/article/details/104043838