PTA:先序輸出葉結點 (20分)

Dogie_Cedrick發表於2020-11-08

先序輸出葉結點 (20分)

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

#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;
}
BinTree CreateTree(BinTree t){
    t=(BinTree)malloc(sizeof(struct TNode));
    char temp;
    scanf("%c",&temp);
    getchar();
    if(temp=='#')
        return NULL;
    t->Data=temp;
    printf("請輸入%c的左子樹:",t->Data);
    t->Left=CreateTree(t->Left);
    printf("請輸入%c的右子樹:",t->Data);
    t->Right=CreateTree(t->Right);
    return t;
}

BinTree CreatBinTree(){
    BinTree t;
    return CreateTree(t);
}
void PreorderPrintLeaves( BinTree BT ){
    if(BT==NULL)
        return;
    if(BT->Left==NULL&&BT->Right==NULL)
        printf(" %c",BT->Data);
    else{
        PreorderPrintLeaves(BT->Left);
        PreorderPrintLeaves(BT->Right);
    }
}

相關文章