栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

03-树2 List Leaves (25 分)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

03-树2 List Leaves (25 分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

结尾无空行

Sample Output:
4 1 5

结尾无空行

#include 
#include 
#include 
#include  
using namespace std;
struct node{
	int ltree,rtree;
};
int buildtree(vector  &a,int n);
int main()
{
	int n;
	cin >> n;
	vector  tree(n);
	int head = buildtree(tree,n);
	queue  bfs;
	queue  result;
	bfs.push(head);
	while(!bfs.empty()){
		int frontnode = bfs.front();
		bfs.pop();
		if(tree[frontnode].ltree==-1&&tree[frontnode].rtree==-1)
			result.push(frontnode);
		if(tree[frontnode].ltree!=-1)
			bfs.push(tree[frontnode].ltree);
		if(tree[frontnode].rtree!=-1)
			bfs.push(tree[frontnode].rtree);
	}
	cout << result.front();
    result.pop();
    while(!result.empty())
    {
        cout << " " << result.front();
        result.pop();
    }
	return 0;
} 
int buildtree(vector  &a,int n)
{
	int head = -1;
	vector ishead(n);
	char c;
	for(int i = 0;i < n;i++){
		cin >> c;
		if(c == '-')
			a[i].ltree = -1;
		else{
			a[i].ltree = c - '0';
			ishead[c - '0'] = 1;
		}
		cin >> c;
		if(c == '-')
			a[i].rtree = -1;
		else{
			a[i].rtree = c - '0';
			ishead[c - '0'] = 1;
		}
	}
	for(int i = 0;i < n;i++)
		if(ishead[i]==0)
			head = i;
	return head;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号