03-樹2 List Leaves輸出葉子結點,二叉樹的層序遍歷

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

題目出處

題目出處:中國大學MOOC-陳越、何欽銘-數據結構

輸入描述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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章