第十周项目2-二叉树遍历的递归算法

/*   

* 烟台大学计算机与控制工程学院   

* 作者:王雪松  

* 完成日期:2016年11月11日   

*   

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

* 输入描述:

* 程序输出:

 */ 

代码: (btreee.h见算法库

//main.cpp

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


运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值