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
輸入第一行給節點數,接下來每行描述該節點的左、右孩子,要我們由上而下、由左至右印出所有葉節點。
最容易搞錯的地方是:輸入的第幾行,就代表編號為幾的節點。以範例為例,第 0 行的「1 -」表示編號 0 的節點左孩子是 1(指向第 1 行),右孩子為空。理解這層對應關係,題目就沒有難點了。
樹的模型如下:
而「由上而下、由左至右」正是層序遍歷(BFS)的天然輸出順序,因此用佇列實作最為直接。
#include <cstdio>
#include <cctype>
#define N 10
typedef struct Node {
int data, left, right;
} TreeNode;
TreeNode node[N];
TreeNode Queue[N]; // 數組實現隊列
int first = -1, last = -1;
void Push(TreeNode tn);
TreeNode Pop();
void printLeaves(int root, int n);
int charToInt(char ch);
int main() {
int n;
bool isRoot[N];
int root;
scanf("%d\n", &n);
for (int i = 0; i < n; i++)
isRoot[i] = 1;
for (int i = 0; i < n; i++) {
char cLeft, cRight;
scanf("%c %c", &cLeft, &cRight);
getchar(); // 讀取緩存區的回車符
node[i].left = charToInt(cLeft);
node[i].right = charToInt(cRight);
node[i].data = i;
// 一個節點的左孩子和右孩子一定不是根節點
if (node[i].left != -1)
isRoot[node[i].left] = 0;
if (node[i].right != -1)
isRoot[node[i].right] = 0;
}
// 找到根節點
for (int i = 0; i < n; i++) {
if (isRoot[i]) {
root = i;
break;
}
}
printLeaves(root, n);
return 0;
}
void Push(TreeNode treeNode) {
Queue[++last] = treeNode;
}
TreeNode Pop() {
return Queue[++first];
}
// 層序遍歷樹節點並打印出葉節點:隊列實現
void printLeaves(int root, int n) {
int leaves[N];
int k = 0;
Push(node[root]);
for (int i = 0; i < n; i++) {
TreeNode tn = Pop();
// 左孩子和右孩子都不存在時,將葉節點的值保存到數組中,便於格式化打印
if (tn.left == -1 && tn.right == -1)
leaves[k++] = tn.data;
if (tn.left != -1)
Push(node[tn.left]);
if (tn.right != -1)
Push(node[tn.right]);
}
for (int i = 0; i < k - 1; i++)
printf("%d ", leaves[i]);
printf("%d\n", leaves[k - 1]);
}
int charToInt(char ch) {
if (isdigit(ch))
return ch - '0';
else
return -1;
}
整體流程可以拆成三步:先掃一遍輸入建立節點表並用 isRoot 標記誰不是根節點,接著找出真正的根,最後走一趟 BFS 收集葉節點。注意 scanf 之後要補一個 getchar() 吃掉換行符,這是字元輸入最常踩到的小坑。