4-11 先序輸出葉結點 (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
#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;
}
/* 你的代碼将被嵌在這裡 */
void PreorderPrintLeaves(BinTree BT) {
if (BT) {
if ((!BT->Left) && (!BT->Right)) // 若是葉節點
printf(" %c", BT->Data);
PreorderPrintLeaves(BT->Left);
PreorderPrintLeaves(BT->Right);
}
}