第九周 【项目2

来源:互联网 发布:免费升级至windows 10 编辑:程序博客网 时间:2024/06/04 18:33

【二叉树遍历的递归算法】 
  实现二叉树的先序、中序、后序遍历的递归算法,并对用”A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))”创建的二叉树进行测试。 

[参考解答]

#include <stdio.h>#include "btree.h"void PreOrder(BTNode *b)        //先序遍历的递归算法{    if (b!=NULL)    {        printf("%c ",b->data);  //访问根节点        PreOrder(b->lchild);    //递归访问左子树        PreOrder(b->rchild);    //递归访问右子树    }}void InOrder(BTNode *b)         //中序遍历的递归算法{    if (b!=NULL)    {        InOrder(b->lchild);     //递归访问左子树        printf("%c ",b->data);  //访问根节点        InOrder(b->rchild);     //递归访问右子树    }}void PostOrder(BTNode *b)       //后序遍历的递归算法{    if (b!=NULL)    {        PostOrder(b->lchild);   //递归访问左子树        PostOrder(b->rchild);   //递归访问右子树        printf("%c ",b->data);  //访问根节点    }}int main(){    BTNode *b;    CreateBTNode(b,"A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))");    printf("二叉树b:");    DispBTNode(b);    printf("\n");    printf("先序遍历序列:\n");    PreOrder(b);    printf("\n");    printf("中序遍历序列:\n");    InOrder(b);    printf("\n");    printf("后序遍历序列:\n");    PostOrder(b);    printf("\n");    DestroyBTNode(b);    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

注:在main函数中,创建的用于测试的二叉树如下—— 
这里写图片描述

原创粉丝点击