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
解:要用到bfs搜索,使用队列进行存储#include <iostream>
#include <queue>
using namespace std;
#define maxTree 10
#define null -1
struct node{
int data;
int left;
int right;
}tree[maxTree];
int N, isRoot[maxTree];
queue<int> Q;
int create_tree(struct node T[]){
int root = null, i;
char cl, cr;
cin>>N;
if(N){
for(i = 0; i < N; i++)
isRoot[i] = 1;
for(i = 0; i < N; i++){
T[i].data = i;
cin>>cl>>cr;
if(cl != '-'){
T[i].left = cl - '0';
isRoot[T[i].left] = 0;
}else{
T[i].left = null;
}
if(cr != '-'){
T[i].right = cr - '0';
isRoot[T[i].right] = 0;
}else{
T[i].right = null;
}
}
for(i = 0; i < N; i++){
if(isRoot[i]) break;
}
root = i;
}
return root;
}
void bfs_find_leaves(int root){
Q.push(root);
int flag = 0;
while(!Q.empty()){
root = Q.front();
Q.pop();
if(tree[root].left == null && tree[root].right == null){
if(flag == 0){
cout<<tree[root].data;
flag = 1;
}else{
cout<<' '<<tree[root].data;
}
}
if(tree[root].left != null){
Q.push(tree[root].left);
}
if(tree[root].right != null){
Q.push(tree[root].right);
}
}
}
int main(){
int root;
root = create_tree(tree);
bfs_find_leaves(root);
return 0;
}2017-4-21 待续
本文介绍了一种使用广度优先搜索(BFS)来遍历树形结构的方法,并通过C++实现,按从上到下、从左到右的顺序列出所有叶子节点的索引。
229

被折叠的 条评论
为什么被折叠?



