List Leaves

<span style="color: rgb(51, 51, 51); font-family: 'Microsoft YaHei', helvetica, sans-serif; font-size: 14px; line-height: 16.8px; background-color: rgb(255, 255, 255);">Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.</span>

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer NN (\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1N1. Then NN 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 <stdio.h>
#include <string.h>
#include <queue>
using namespace std;

struct treenode {
	int left;
	int right;
}t1[15];
int createtree(struct treenode t[],int n) {
	int root = -1;
	if (n) {
		int i, c[15]; char cl, cr;
		memset(c, 0, sizeof(c));
		for (i = 0; i < n; i++) {
			getchar();
			scanf("%c %c", &cl, &cr);
			if (cl != '-') {
				t[i].left = cl - '0';
				c[t[i].left] = 1;
			}
			else t[i].left = -1;
			if (cr != '-') {
				t[i].right = cr - '0';
				c[t[i].right] = 1;
			}
			else t[i].right = -1;
		}
		for (i = 0; i < n; i++)
			if (!c[i]) break;
		root = i;
	}
	return root;
}

int main()
{
	int flag = 0;
	int r1,i,n;
	scanf("%d", &n);
	queue<int>qu;
	r1 = createtree(t1, n);
	qu.push(r1);
	while (qu.size()) {
		int s = qu.front();
		qu.pop();
		if (t1[s].left != -1) qu.push(t1[s].left);
		if (t1[s].right != -1) qu.push(t1[s].right);
		if (t1[s].left == -1 && t1[s].right == -1) {
			if (!flag) flag = 1;
			else printf(" ");
			printf("%d", s);
		}
	}
	printf("\n");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/xmzyjr123/article/details/51997696