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
一定要注意输出的最后一个结果后面是没有空格的(5后面没有空格),不然程序也是无法通过的,所以注意这个细节的处理。
#include<iostream>
using namespace std;
//#define Null -1;
#define Null -1
//想法是这样的:采用层次遍历输出,判断父结点左右孩子是否为空,为空则为叶子结点
struct Node
{
int left;
int right;
};
int main()
{
//建树
Node arr[10];
int N;
int count=0;
cin>>N;
char a,b;
//还必须获得头结点的地址
int arr2[10]={0};
for(int i=0;i<N;i++)
{
cin>>a>>b;
if(a!='-')
{
arr[i].left=a-'0';
arr2[arr[i].left]=1;
}
else
arr[i].left=Null;
if(b!='-')
{
arr[i].right=b-'0';
arr2[arr[i].right]=1;
}
else
arr[i].right=Null;
if(a=='-'&&b=='-')
count++;
}
//找头结点地址
int i;
for(i=0;i<N;i++)
{
if(arr2[i]==0)
break;
}
//树建好后,开始层次遍历,队里面应该放的是数组的下标
int que[10];
int front=-1,rear=-1;
//首结点先入队
que[++rear]=i;
while(front<rear)
{
//出队
i=que[++front];
if(arr[i].left!=Null)
que[++rear]=arr[i].left;
if(arr[i].right!=Null)
que[++rear]=arr[i].right;
if(arr[i].left==Null&&arr[i].right==Null)
{
cout<<i;
count--;
if(count)printf(" ");//注意空格的处理
}
}
return 0;
}