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("
");
   printf("Inorder:");    Inorder(T);    printf("
");
   printf("Postorder:");  Postorder(T);  printf("
");
   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);
}
原文地址:https://www.cnblogs.com/DirWang/p/11929992.html