1. 程式人生 > >樹2 List Leaves (中國大學MOOC-陳越、何欽銘-資料結構-2018秋)

樹2 List Leaves (中國大學MOOC-陳越、何欽銘-資料結構-2018秋)

03-樹2 List Leaves (25 point(s))

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<cstring>
using namespace std;
#define MAXsize 10
#define Null -1
struct TreeNode
{
	int left;
	int right;
}T1[MAXsize];
int Buildtree(struct TreeNode t[])
{
	int N, root;
	cin >> N;
	if (!N) return Null;
	int *check = new int[N];
	for (int i = 0; i < N; i++)
	{
		check[i] = 0;
	}
	for (int i = 0; i < N; ++i) {
		char tcl, tcr;
		cin >> tcl >> tcr;
		if (tcl != '-') {
			t[i].left= tcl - '0';
			check[t[i].left] = 1;
		}
		else t[i].left =Null;
		if (tcr != '-') {
			t[i].right= tcr - '0';
			check[t[i].right] = 1;
		}
		else t[i].right = Null;
	}
	int index;
	for (index = 0; index < N; ++index) {
		if (!check[index]) break;
	}
	root = index;
	return root;
}
int leaves(int R) {
	if (R == Null) return 0;
	int front=0, rear=0,flag=1;
	int queue[10];
	queue[rear] = R;
	rear++;
	int temp = 0;
	while (front!=rear)
	{
		temp = queue[front];
		if ((T1[temp].left == Null) && (T1[temp].right == Null))
		{
			if (flag)
			{
				printf("%d", temp); flag = 0;
			}
			else
			{
				printf(" %d", temp);
			}
		
		}
		if (T1[temp].left!=Null)
		{
			queue[rear] = T1[temp].left;
			rear++;
		}
		if (T1[temp].right!= Null)
		{
			queue[rear] = T1[temp].right;
			rear++;
		}
		front++;
	}
	return 0;
}
int main()
{
	int R1;
	R1 = Buildtree(T1);
	leaves(R1);
	return 0;
}