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

来源:互联网 发布:js 设置 form action 编辑:程序博客网 时间:2024/06/06 19:57
  1. /*  
  2. Copyright (c)2016,烟台大学计算机与控制工程学院  
  3. All rights reserved.  
  4. 文件名称:第十周项目2 - 二叉树遍历的递归算法.cpp  
  5. 作    者:陈晓琳  
  6. 完成日期:2016年11月3日  
  7. 版 本 号:v1.0  
  8. 问题描述:  实现二叉树的先序、中序、后序遍历的递归算法,并对用”A(B(D,E(H(J,K(L,M(,N))))),C(F,G(,I)))”创建的二叉树进行测试。  
  9.          请利用二叉树算法库。  
  10. 输入描述: 若干测试数据。  
  11. 程序输出: 二叉树的输出。  
  12. */   

头文件及功能函数见【二叉树算法库】

代码:

[cpp] view plain copy
  1. #include "btree.h"    
  2.     
  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 0
原创粉丝点击