题目描述

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.

1
2
3
4
5
6
7
8
9
10
11
12
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
4 1 5

分析

  • 因为要全部数据输入完后才能知道根节点是哪个(没有结点指向的就是根节点),所以采用静态链表的形式存储
  • 遍历找出左右孩子都是NULL的即为叶子结点

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
#include<queue>
using namespace std;

struct TreeNode {
int left;
int right;
}bintrees[15];

queue<int> q;
int first = 1;

int buildTree() {
int n;
char left, right;
int checked[15] = { 0 };

cin >> n;
for (int i = 0; i < n; i++) {
cin >> left >> right;
if (left != '-') {
bintrees[i].left = left - '0';
checked[bintrees[i].left] = 1;
}
else
bintrees[i].left = -1;
if (right != '-') {
bintrees[i].right = right - '0';
checked[bintrees[i].right] = 1;
}
else
bintrees[i].right = -1;
}
for (int i = 0; i < n; i++) {
if (checked[i] == 0)
return i;
}
}

void travelTree() {
int now;

while (true) {
now = q.front();
q.pop();
if (bintrees[now].left == -1 && bintrees[now].right == -1) {
if (!first)
cout << ' ';
first = 0;
cout << now;
}
if (bintrees[now].left != -1)
q.push(bintrees[now].left);
if (bintrees[now].right != -1)
q.push(bintrees[now].right);
if (q.empty())
break;
}
}

int main() {
int root;

root = buildTree();
q.push(root);
travelTree();
return 0;
}