C++ 实现静态二叉树的层次并列

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

 这其实是一道综合题,读入是静态二叉树,每一行只给出左右儿子,其中根为序号i-1,在使用层次遍历即可,层次遍历借出队列实现。可以使用STL标准模板库中实现好的

#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1



struct TreeNode
{
	ElementType Element;
	Tree Left;
	Tree Right;
}T1[MaxTree];

Tree BuildTree(TreeNode T[]);
void findLeaf(Tree R);

int main()
{
	Tree R;
	R= BuildTree(T1);
	findLeaf(R);
	return 0;
}

Tree BuildTree(TreeNode T[])
{
	int N;
	char cl, cr;
	int check[MaxTree];       // 判断每一个节点有没有节点指向
	int Root = Null;
	scanf_s("%d\n", &N);
	if (N)
	{
		for (int i = 0; i < N; i++)
			check[i] = 0;
		for (int i = 0; i < N; i++)
		{
			T[i].Element = i;
			scanf_s("%c %c\n", &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;
			}
		}
		for (int i = 0; i < N; i++)
		{
			if (!check[i])
			{
				Root = i;
				break;
			}
		}
	}
	return Root;
}

void findLeaf(Tree R) {
	queue<int> q;
	int flag = 1;
	if (R == Null)
		return;
	q.push(R);
	int temp = 0;
	while (!q.empty()) {
		//printf("no empty\n");
		temp = q.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)
			q.push(T1[temp].Left);
		if (T1[temp].Right != Null)
			q.push(T1[temp].Right);
		q.pop();
	}
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/82803221