03-树2 List Leaves (25分)

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 NN (\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1N1. Then NN 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

意思就是输出所有子节点就可以了,按照从左到右,从上到下的顺序。用数组存储二叉树,然后用队列bfs层序遍历即可,找到左右节点都为空即可输出,比较简单。

#include<iostream>
#include<queue>
using namespace std;
struct node
{
	int key,left,right;
}a[11];
int check[11];
void judge(int x)
{
	queue<node>q;
	q.push(a[x]);
		while(!q.empty())
		{
			node temp=q.front();
			q.pop();
			if(temp.left==-1&&temp.right==-1&&!q.empty())
			{
				cout<<temp.key<<" ";
			}
			else if(temp.left==-1&&temp.right==-1&&q.empty())
			{
				cout<<temp.key<<endl;
			}
			else
			{
				if(temp.left!=-1)
				{
					q.push(a[temp.left]);
				}
				if(temp.right!=-1)
				{
					q.push(a[temp.right]);
				}
			}
		}
}
int main()
{
	int root;
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		a[i].key=i;
		char l,r;
		cin>>l>>r;
		if(l!='-')
		{
			a[i].left=l-'0';
			check[l-'0']=1;
		}
		else
		{
			a[i].left=-1;
		}
		if(r!='-')
		{
			a[i].right=r-'0';
			check[r-'0']=1;
		}
		else
		{
			a[i].right=-1;
		}
	}
	for(int i=0;i<n;i++)
	{
		if(!check[i])
		{
			root=i;
			a[root].key=i;
			break;
		}
	}
	judge(root);
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没想好叫什么名字

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值