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 <iostream>
#include <queue>
using namespace std;
const int N = 10;
const int Null = -1;
typedef int Tree;

struct TreeNode {
	Tree left;
	Tree right;
}T[N];

Tree BuildTree(TreeNode []);
void TraTree(Tree);

int main(void) {
	Tree R;
	R = BuildTree(T);
	TraTree(R);
	return 0;
}

Tree BuildTree(TreeNode T[]) {
	int n;
	Tree r = Null;
	scanf("%d", &n);
	if (n) {
		int i, check[N];
		char ch, cl, cr;
		for (i = 0;i < n;i++)
			check[i] = 0;
		for (i = 0;i < n;i++) {
			while ((ch = getchar()) != '\n')
				continue;
			scanf("%c %c", &cl, &cr);
			if (cl != '-') {
				T[i].left = cl - '0';
				check[T[i].left] = 1;
			}
			else
				T[i].left = Null;
			if (cr != '-') {
				T[i].right = cr - '0';
				check[T[i].right] = 1;
			}
			else
				T[i].right = Null;
		}
		r = 0;
		while (check[r]) r++;
	}
	return r;
}

void TraTree(Tree r) {
	queue<int> q;
	int t;
	int flag = 0;
	if (r != Null) {
		q.push(r);
		while (!q.empty()) {
			t = q.front();
			q.pop();
			if (T[t].left != Null)
				q.push(T[t].left);
			if (T[t].right != Null)
				q.push(T[t].right);
			if ((T[t].left == Null) && (T[t].right == Null)) {
				if (flag)
					printf(" ");
				else
					flag = 1;
				printf("%d", t);
			}
		}
	}

}



發佈了35 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章