1. 程式人生 > >第六章樹和二叉樹作業1—二叉樹--計算機17級 6-2 二叉樹的遍歷 (25 分)

第六章樹和二叉樹作業1—二叉樹--計算機17級 6-2 二叉樹的遍歷 (25 分)

6-2 二叉樹的遍歷 (25 分)

本題要求給定二叉樹的4種遍歷。

函式介面定義:

void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

其中BinTree結構定義如下:

typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

要求4個函式分別按照訪問順序打印出結點的內容,格式為一個空格跟著一個字元。

裁判測試程式樣例:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 實現細節忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

int main()
{
    BinTree BT = CreatBinTree();
    printf("Inorder:");    InorderTraversal(BT);    printf("\n");
    printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
    printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
    printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
    return 0;
}
/* 你的程式碼將被嵌在這裡 */

輸出樣例(對於圖中給出的樹):

Inorder: D B E F A G H C I
Preorder: A B D F E C G H I
Postorder: D E F B H G I C A
Levelorder: A B C D F G I E H

 前序,中序,後序都很簡單,普通遞迴遍歷就好,層序的話就有難度了。正常來講會使用佇列來實現,但是由於這是道函式題,沒辦法實現佇列,所以只能用陣列來模擬

四個函式程式碼實現如下:

void PreorderTraversal( BinTree BT )//前序遍歷 
{
	if(BT)
	{
		printf(" %c",BT->Data);
		PreorderTraversal( BT->Left );
		PreorderTraversal( BT->Right );
	} 
	else
	    return ;
} 
void InorderTraversal( BinTree BT )//中序遍歷 
{
	if(BT)
	{
		InorderTraversal( BT->Left );
		printf(" %c",BT->Data);
		InorderTraversal( BT->Right );
	} 
	else
	return ;

} 


void PostorderTraversal( BinTree BT )//後序遍歷 
{
	if(BT)
	{
		PostorderTraversal( BT->Left );
		PostorderTraversal( BT->Right );
		printf(" %c",BT->Data);
	} 
	else
	return;

} 
void LevelorderTraversal( BinTree BT )//層序遍歷 
{
	if(BT == NULL)
	    return;
	BinTree p[101];
	int shuzu = 0,index = 0;//兩個都是下標,前者儲存原陣列,後者儲存層序遍歷的次序 
	p[index++] = BT;
	while(shuzu < index)
	{
		BinTree q = p[shuzu++];
		printf(" %c",q->Data);//逐層輸出結點 ,然後將他的兩個孩子放入下標陣列中 
		if(q->Left != NULL)
		{
			p[index++] = q->Left;
		}
		if(q->Right != NULL)
		{
			p[index++] = q->Right;
		}
	}
	
}