# 輸出葉子結點，二叉樹的層序遍歷

## 輸入描述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.

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

4 1 5

## C語言代碼實現

``````#include <stdio.h>
#include <stdlib.h>
#define maximum 10

typedef struct tnode
{
int left;
int right;
}tnode;

typedef struct queue
{
int front;
int rear;
int data[maximum];
}queue;

tnode tree[maximum];
queue que;
int leaves[maximum];

int build(tnode tree[])
{
int check[maximum] = {0}, i, n;
char l, r;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf(" %c %c", &l, &r);
if (l == '-') tree[i].left = -1;
else
{
tree[i].left = l - '0';
check[tree[i].left] = 1;
}
if (r == '-') tree[i].right = -1;
else
{
tree[i].right = r - '0';
check[tree[i].right] = 1;
}
}
for (i = 0; i < n; i++) if (!check[i]) break;
return i;
}

void init(queue *que)
{
que->front = que->rear = 0;
}

int isempty(queue que)
{
if (que.front == que.rear) return 1;
else return 0;
}

int pop(queue *que)
{
int x;
if (isempty(*que)) return -1;
else
{
x = que->data[que->front];
que->front = (que->front + 1) % maximum;
return x;
}
}

void push(queue *que, int x)
{
que->data[que->rear] = x;
que->rear = (que->rear + 1) % maximum;
}

void travel(int root)
{
int n=0, i;
do
{
if(tree[root].left == -1 && tree[root].right == -1) leaves[n++] = root;
if(tree[root].left != -1) push(&que, tree[root].left);
if(tree[root].right != -1) push(&que, tree[root].right);
root = pop(&que);
}while (root != -1);
for (i = 0; i < n-1; i++) printf("%d ", leaves[i]);
printf("%d", leaves[n-1]);
}

int main(int argc, char *argv[]) {
int root;
root = build(tree);
init(&que);
travel(root);
return 0;
}
``````