二叉树的数组表示建立以及层序遍历叶节点

7-4 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

输入数据的形式是0到N-1表示节点编号,两个数字表示左右儿子的编号。

读取的时候,用字符串读取,如果是-,则说明没有对应儿子,如果读到数,在转化为整形,然后需要寻找根节点。根节点的特点是没有指向他的节点。这样可以在遍历时查找,显然本题给定样例,根即为3。因为3没有出现过。最后返回根节点的值。

遍历的时候中序遍历需要借助队列实现,判断是否为叶,如果叶子,就输出

下面的实现为了简单,树的实现用了全局的数组遍量实现。

#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("%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("%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()) 
	{
		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/83589128
今日推荐