PTA 二叉樹的三種遍歷(先序、中序和后序)


6-5 二叉樹的三種遍歷(先序、中序和后序) (6 分)
 

本題要求實現給定的二叉樹的三種遍歷。

函數接口定義:


void Preorder(BiTree T);
void Inorder(BiTree T);
void Postorder(BiTree T);

T是二叉樹樹根指針,Preorder、Inorder和Postorder分別輸出給定二叉樹的先序、中序和后序遍歷序列,格式為一個空格跟着一個字符。

其中BinTree結構定義如下:

typedef char ElemType;
typedef struct BiTNode
{
   ElemType data;
   struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

裁判測試程序樣例:


#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;
typedef struct BiTNode
{
   ElemType data;
   struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

BiTree Create();/* 細節在此不表 */

void Preorder(BiTree T);
void Inorder(BiTree T);
void Postorder(BiTree T);

int main()
{
   BiTree T = Create();
   printf("Preorder:");   Preorder(T);   printf("\n");
   printf("Inorder:");    Inorder(T);    printf("\n");
   printf("Postorder:");  Postorder(T);  printf("\n");
   return 0;
}
/* 你的代碼將被嵌在這里 */

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

二叉樹.png

Preorder: A B D F G C
Inorder: B F D G A C
Postorder: F G D B C A

void Preorder(BiTree T){
    if(T==NULL)
        return;
    printf(" %c",T->data);
    Preorder(T->lchild);
    Preorder(T->rchild);
}
void Inorder(BiTree T){
    if(T==NULL)
        return;
    Inorder(T->lchild);
    printf(" %c",T->data);
    Inorder(T->rchild);
}
void Postorder(BiTree T){
    if(T==NULL)
        return;
    Postorder(T->lchild);
    Postorder(T->rchild);
    printf(" %c",T->data);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM