03-树2 List Leaves (25分)

来源:互联网 发布:怎么删除管家婆数据 编辑:程序博客网 时间:2024/05/17 05:01

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 NN (\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1N1. 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:

81 -- -0 -2 7- -- -5 -4 6

Sample Output:

4 1 5
解:要用到bfs搜索,使用队列进行存储
C++代码:
#include <iostream>#include <queue>using namespace std;#define maxTree 10#define null -1struct 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 待续
0 0