7-9 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
Ac代码:
#include<cstdio>//题目的条件相对宽松
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
char a[15][3];
int vis[11] = {0},b[30];
int main()
{
int t;
cin>>t;
for(int i = 0;i<t;i++)
{
cin>>a[i][0]>>a[i][1];
if(a[i][0]!='-') vis[a[i][0]-'0']++;
if(a[i][1]!='-') vis[a[i][1]-'0']++;
}
queue<int>s;
for(int i = 0;i<t;i++)
{
if(vis[i]==0)
{
s.push(i);
break;
}
}
int v,t1 = 0;
while(!s.empty())
{
v = s.front();
s.pop();
b[t1++] = v;
if(a[v][0]!='-')
{
s.push(a[v][0]-'0');
}
if(a[v][1]!='-')
{
s.push(a[v][1]-'0');
}
}
int j = 0;
for(int i = 0;i<t1;i++)
{
if(a[b[i]][0]=='-'&&a[b[i]][1]=='-')
{
if(j!=0) printf(" ");
printf("%d",b[i]);
j++;
}
}
return 0;
}