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-1N−1. 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
题目代码实现:
#include <iostream>
#include <queue>
#include <stdlib.h>
using namespace std;
#define MaxTree 10
#define Tree int
#define Null -1
struct TreeNode{
Tree Left;
Tree Right;
}T1[MaxTree];
int r[MaxTree];
Tree BuildTree(struct TreeNode T[]){
int N=0;
int i=0;
char cl,cr;
int check[MaxTree];
Tree Root=0;
cin>>N;
if (N) {
for (i=0;i<N;i++) {
check[i]=0;
}
for (i=0;i<N;i++) {
cin>>cl>>cr;
if (cl!='-') {
T[i].Left=cl-'0';
check[T[i].Left]=1;
}
else {
T[i].Left=Null;
}
//对cr的对应处理
if (cr!='-') {
T[i].Right=cr-'0';
check[T[i].Right]=1;
}
else {
T[i].Right=Null;
}
}
for (i=0;i<N;i++) {
if (!check[i]) {
break;
}
}
Root=i;
}else {
Root=-1;
}
return Root;
}
//用队列实现层序遍历
void LevelOrderTraversal(Tree R1){
queue<int> Q;
int flag=0;
Tree T;
T=R1;
int i=0;
if (R1==Null) {
return;
}
Q.push(T);
//cout << Q.size()<<endl;
while (!Q.empty()) {
T=Q.front();
if (T!=Null) {
if (T1[T].Left==Null&&T1[T].Right==Null) {
//flag对输出格式的控制
if (!flag) {
flag=1;
}else {
cout<<" ";
}
cout<<T;
Q.pop();
}
else {
Q.pop();
}
if (T1[T].Left!=Null) {
Q.push(T1[T].Left);
}
if (T1[T].Right!=Null) {
Q.push(T1[T].Right);
}
}
}
}
int main(int argc, char *argv[]) {
Tree R1;
R1=BuildTree(T1);
LevelOrderTraversal(R1);
}