1. 程式人生 > >資料結構 先序輸出葉子節點

資料結構 先序輸出葉子節點

6-11 先序輸出葉結點 (15 point(s))

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

函式介面定義:

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 == NULL)
		return;

	if (BT->Left == NULL && BT->Right == NULL)
		printf(" %c", BT->Data);

	PreorderPrintLeaves(BT->Left);
	PreorderPrintLeaves(BT->Right);


	
}