第九周项目二

来源:互联网 发布:哈尔滨软件开发88087 编辑:程序博客网 时间:2024/05/16 14:02
【二叉树遍历的递归算法】 

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

[cpp] view plain copy print?
  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. }  
运行结果: