Problem Description
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
Solution
题意很好理解:层序遍历输出树的叶结点。
数据存储方式与 03-树1 树的同构 是相似的,只需略作修改即可直接套用上一题的读入函数。甚至找根结点下标的方法也是一样的。
层序遍历需要用到队列这一数据结构,在此题中为了避免 C 语言繁琐的规范数据结构声明(如果用 C++ 可以直接使用模板),使用了双指针与数组构造了一个简易的队列。
层序遍历算法:
- 先将树的根节点入队,进入循环(如果本身是空树,根结点就不入队,队列为空,不进入循环)
- 队列是否为空
- 队列非空就将队首元素出队,判断是否为叶结点:
- 若为叶结点就访问
- 若不为叶结点就不做操作
- 然后将该结点的左右子树的根结点下标入队(如果左或右子树为空就不用入队)
- 继续循环
- 循环退出条件为队列为空,即所有结点都遍历完毕
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
int left;
int right;
} TNode;
int front = 0, rear = 0, queue[10];
int first = 1;
int Create(TNode *T)
{
int i, n, root;
char nodel, noder;
scanf("%d", &n);
getchar();
if (n == 0)
root = -1;
else {
root = 0;
for (i = 0; i < n; i++) {
scanf("%c %c", &nodel, &noder);
getchar();
T[i].data = i;
if (nodel != '-') {
T[i].left = nodel - '0';
root -= T[i].left;
} else
T[i].left = -1;
if (noder != '-') {
T[i].right = noder - '0';
root -= T[i].right;
} else
T[i].right = -1;
root += i;
}
}
return root;
}
void LevelOrderTraversal(TNode *T, int root)
{
if (root != -1) {
queue[rear] = root;
rear++;
}
while (front < rear) {
root = queue[front];
front++;
if (T[root].left == T[root].right)
if (first) {
printf("%d", T[root].data);
first = 0;
} else {
printf(" %d", T[root].data);
}
if (T[root].left != -1) {
queue[rear] = T[root].left;
rear++;
}
if (T[root].right != -1) {
queue[rear] = T[root].right;
rear++;
}
}
}
int main()
{
int root;
TNode T[10];
root = Create(T);
LevelOrderTraversal(T, root);
return 0;
}