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.
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode{
char left;
char right;
}T[10];
//创建一颗树
int BuildTree(struct TreeNode T[]);
//层序遍历二叉树
void tranverseTree(struct TreeNode T[], int tree);
int main()
{
//输入
int tree = BuildTree(T);
//层序遍历二叉树,输出叶子结点
tranverseTree(T, tree);
return 0;
}
//创建一颗树
int BuildTree(struct TreeNode T[])
{
int root = -1;
int i, N;
char cr, cl;
int check[10];
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 = -1;
if(cr != '-'){
T[i].right = cr - '0';
check[T[i].right] = 1;
}
else T[i].right = -1;
}
for(i = 0; i < N; i++){
if(!check[i]) break;
}
root = i;
}
return root;
}
//层序遍历二叉树
void tranverseTree(struct TreeNode T[], int tree)
{
if(tree == -1) return;
bool flg = false; //记录是否是第一个叶子结点
queue<int> que;
que.push(tree);
while(!que.empty()){
int node = que.front();
que.pop();
if(T[node].left == -1 && T[node].right == -1) {
if(flg) cout << " " << node;
else{
cout << node;
flg = true;
}
}
if(T[node].left != -1) que.push(T[node].left);
if(T[node].right != -1) que.push(T[node].right);
}
}