# 03-2. List Leaves (25)

400 ms

65536 kB

8000 B

Standard

CHEN, Yue

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 <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
#define lson ((root<<1)+1)
#define rson ((root<<1)+2)
#define MID ((l+r)>>1)
typedef long long ll;
typedef pair<int,int> P;
#define For(i,t,n) for(int i=(t);i<(n);i++)
const int maxn=201;
const int base=1000;
const int inf=9999999;
const double eps=1e-5;
int T[maxn];
int f[maxn];//用于标记   寻找根，没有出现的就是根
int n;
int main()
{
int m,i,j,k,t;
cin>>n;
memset(T,-1,sizeof(T));
memset(f,0,sizeof(f));
for(i=0;i<n;i++)
{
int l,r;
char s[3],u[3];
scanf("%s%s",u,s);
if(s[0]=='-')
r=-1;
else
r=atoi(s);
if(u[0]=='-')
l=-1;
else
l=atoi(u);

T[(i<<1)+1]=l;
T[(i<<1)+2]=r;
f[l]++;
f[r]++;
}
for(i=0;i<n;i++)
if(f[i]==0)break;

queue<int> q;//树的层次遍历
q.push(i);
int first=1;
while(!q.empty())
{
int root=q.front();
q.pop();
if(T[rson]==-1&&T[lson]==-1)
{
if(first)
{
first=0;
printf("%d",root);
}
else
printf(" %d",root);
}
if(T[lson]!=-1)
q.push(T[lson]);
if(T[rson]!=-1)
q.push(T[rson]);
}
printf("\n");
return 0;
}