1. 程式人生 > >第六章樹和二叉樹作業1—二叉樹--計算機17級 6-3 先序輸出葉結點 (15 分)

第六章樹和二叉樹作業1—二叉樹--計算機17級 6-3 先序輸出葉結點 (15 分)

6-3 先序輸出葉結點 (15 分)

本題要求按照先序遍歷的順序輸出給定二叉樹的葉結點。

函式介面定義:

void PreorderPrintLeaves( BinTree BT );

其中BinTree結構定義如下:

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

函式PreorderPrintLeaves應按照先序遍歷的順序輸出給定二叉樹BT

的葉結點,格式為一個空格跟著一個字元。

裁判測試程式樣例:

#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 PreorderPrintLeaves( BinTree BT );

int main()
{
    BinTree BT = CreatBinTree();
    printf("Leaf nodes are:");
    PreorderPrintLeaves(BT);
    printf("\n");

    return 0;
}
/* 你的程式碼將被嵌在這裡 */

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

Leaf nodes are: D E H I

 沒啥難的。。。看程式碼吧。。。

void PreorderPrintLeaves( BinTree BT )
{
	if(BT)
	{
		if(!BT->Left&&!BT->Right)//判斷是不是葉子結點
			printf(" %c",BT->Data);
		PreorderPrintLeaves( BT->Left );
		PreorderPrintLeaves( BT->Right );
	}
	else
	    return ;
}