数据结构-2019春 03-树2 List Leaves (25 分)

03-树2 List Leaves (25 分)
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

使用一个队列
二叉树按层遍历即可

#include 
struct tre {
	int lefttree;
	int righttree;
};
struct seq {
	int line[40];
	int front;
	int rear;
}queue;
void inqueue(int x) {
	queue.line[queue.rear] = x;
	queue.rear++;
}
int dequeue() {
	int temp;
	temp = queue.line[queue.front];
	queue.front++;
	return temp;
}


struct tre tree[15];
int visit[20];
int leaves;
void traveltree(int x) {
	if (tree[x].lefttree == -1 && tree[x].righttree == -1) {
		if (leaves > 1) {
			printf("%d ", x);
			leaves--;
		}
		else if (leaves == 1) {
			printf("%d\n", x);
		}
	}

	if (tree[x].lefttree != -1) {
		inqueue(tree[x].lefttree);
	}
	if (tree[x].righttree != -1) {
		inqueue(tree[x].righttree);
	}
	if (queue.front != queue.rear)traveltree(dequeue());
	return;
}


int main() {
	//queue.front = -1;
	//queue.rear = -1;
	int n, i, start;
	char left, right, space;
	scanf("%d", &n);
	getchar();
	for (i = 0; i < n; i++) {
		scanf("%c%c%c", &left, &space, &right);
		getchar();
		if (left != '-') {
			tree[i].lefttree = left - 48;
			visit[tree[i].lefttree] = 1;
		}
		else if (left == '-') {
			tree[i].lefttree = -1;
		}

		if (right != '-') {
			tree[i].righttree = right - 48;
			visit[tree[i].righttree] = 1;
		}
		else if (right == '-') {
			tree[i].righttree = -1;
		}

		if (left == '-'&&right == '-') {
			leaves++;
		}
	}
	for (i = 0; i < n; i++) {
		if (visit[i] == 0) {
			start = i;
			break;
		}
	}
	traveltree(start);
	return 0;
}

你可能感兴趣的:(数据结构-2019春 03-树2 List Leaves (25 分))