03-树2 List Leaves输出叶子结点,二叉树的层序遍历
输出叶子结点,二叉树的层序遍历
题目出处
输入描述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.
大意是给出最多10个正数,形成一棵树,正数编号为0-9,第一行输入为结点个数N,下面每行有两个输入,代表该结点的左右儿子的序号。例如第二行输入为1 -,代表编号为0的结点左儿子序号为1,没有右儿子。第三行输入为- -,代表编号为1的结点既没有左儿子也没有右儿子。
输出描述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
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;
}