1. 程式人生 > >二叉樹的陣列表示建立以及層序遍歷葉節點

二叉樹的陣列表示建立以及層序遍歷葉節點

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();
	}
}