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
/* 层序输出叶子节点。比较简单的一题。。
*/
#include "iostream"
#include "cstring"
#include "queue"
using namespace std;
struct Node {
int data;
int left = -1;
int right = -1;
}s1[15];
bool flag[15];
void bfs(int root) {
int cnt = 1;
queue<Node>q;
q.push(s1[root]);
while (!q.empty()) {
Node t = q.front();
if (t.left == -1 && t.right == -1) {
if (cnt == 1) {
cout << t.data;
cnt++;
}
else {
cout << " " << t.data;
}
}
if (t.left != -1) {
q.push(s1[t.left]);
}
if (t.right != -1) {
q.push(s1[t.right]);
}
q.pop();
}
}
int main() {
int n;
cin >> n;
memset(flag, 0, sizeof(flag));
for (int i = 0; i < n; i++) {
char a, b;
cin >> a >> b;
s1[i].data = i ;
if (a != '-') {
s1[i].left = a-'0';
flag[a-'0'] = 1;
}
if (b != '-') {
s1[i].right = b-'0';
flag[b-'0'] = 1;
}
}
int root = -1;
for (int i = 0; i < n; i++) { /* 找到根节点 */
if (!flag[i]) {
root = i;
break;
}
}
bfs(root);
cout << endl;
return 0;
}
本文介绍了一种算法,该算法能够按照从上到下、从左到右的顺序输出一棵树的所有叶子节点的索引。通过使用队列进行广度优先搜索,并在遍历过程中识别并打印叶子节点来实现。
471

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



