Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
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.
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.
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
4 1 5
#include<iostream>
#include<queue>
using namespace std;
struct PNode{
int Left;
int Right;
int num;
}T1[50];
int BuiltTree(struct PNode T[]);
void LevelOrderTraversal(struct PNode T[],int root);
int main(){
int Root;
Root=BuiltTree(T1);
LevelOrderTraversal(T1,Root);
return 0;
}
int BuiltTree(struct PNode T[]){
int N,Root=-1;
char cl,cr;
cin>>N;
int check[N]={0};
if(N){
for(int i=0;i<N;i++){
cin>>cl>>cr;
T[i].num=i;
if(cl!='-'){
T[i].Left=cl-'0';
check[T[i].Left]=1;
}else{
T[i].Left=-1;
}
if(cr!='-'){
T[i].Right=cr-'0';
check[T[i].Right]=1;
}else{
T[i].Right=-1;
}
}
int j;
for(j=0;j<N;j++){
if(!check[j])break;
}
Root=j;
}
return Root;
}
void LevelOrderTraversal(struct PNode T[],int root){
queue<int>Q;
int i,flag=0;
if(root==-1)return ;
Q.push(root);
while(!Q.empty()){
i=Q.front();
Q.pop();
if(T[i].Left!=-1)Q.push(T[i].Left);
if(T[i].Right!=-1)Q.push(T[i].Right);
if(T[i].Left==-1&&T[i].Right==-1){
if(flag){
printf(" ");
}else{
flag=1;
}
cout<<i;
}
}
}