zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    CSS3 not
    rxjs1
    Angular 2 组件之间如何通信?
    开发去。。
    补零补零
    MySQL数据库从复制及企业配置实践
    互联网中接口安全解决方案
    redis服务打不开--解决办法
    搭建Git服务器
    git将当前分支上修改的东西转移到新建分支
  • 原文地址:https://www.cnblogs.com/DirWang/p/11929992.html
Copyright © 2011-2022 走看看