1. 程式人生 > 其它 >先序輸出葉結點

先序輸出葉結點

先序輸出葉結點

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

函式介面定義

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 == NULL && BT->Right == NULL) /* 如果沒有左子樹也沒有右子樹,則說明是葉子結點 */
            printf(" %c", BT->Data); /* 輸出葉子結點 */
        PreorderPrintLeaves(BT->Left);
        PreorderPrintLeaves(BT->Right);
    }
}