二叉树的四种遍历算法

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #define MaxSize 100
  4. #define MaxWidth 40
  5. typedef char ElemType;
  6. typedef struct tnode
  7. {
  8. ElemType data;
  9. struct tnode *lchild,*rchild;
  10. } BTNode;
  11. void CreateBTree(BTNode * &bt,char *str) /*由str创建二叉链bt*/
  12. {
  13. BTNode *St[MaxSize],*p=NULL;
  14. int top=-1,k,j=0;
  15. char ch;
  16. bt=NULL; /*建立的二叉树初始时为空*/
  17. ch=str[j];
  18. while (ch!='\0') /*str未扫描完时循环*/
  19. {
  20. switch(ch)
  21. {
  22. case '(':top++;St[top]=p;k=1; break; /*为左孩子结点*/
  23. case ')':top--;break;
  24. case ',':k=2; break; /*为孩子结点右结点*/
  25. default:p=(BTNode *)malloc(sizeof(BTNode));
  26. p->data=ch;p->lchild=p->rchild=NULL;
  27. if (bt==NULL) /**p为二叉树的根结点*/
  28. bt=p;
  29. else /*已建立二叉树根结点*/
  30. { switch(k)
  31. {
  32. case 1:St[top]->lchild=p;break;
  33. case 2:St[top]->rchild=p;break;
  34. }
  35. }
  36. }
  37. j++;
  38. ch=str[j];
  39. }
  40. }
  41. void DispBTree(BTNode *bt) /*以括号表示法输出二叉树*/
  42. {
  43. if (bt!=NULL)
  44. {
  45. printf("%c",bt->data);
  46. if (bt->lchild!=NULL || bt->rchild!=NULL)
  47. {
  48. printf("(");
  49. DispBTree(bt->lchild); /*递归处理左子树*/
  50. if (bt->rchild!=NULL)
  51. printf(",");
  52. DispBTree(bt->rchild); /*递归处理右子树*/
  53. printf(")");
  54. }
  55. }
  56. }
  57. // 先序遍历序列
  58. void PreOrder(BTNode *bt)
  59. {
  60. if (bt!=NULL)
  61. {
  62. printf("%c ",bt->data);
  63. PreOrder(bt->lchild);
  64. PreOrder(bt->rchild);
  65. }
  66. }
  67. // 中序遍历序列
  68. void InOrder(BTNode *bt)
  69. {
  70. if (bt!=NULL)
  71. {
  72. InOrder(bt->lchild);
  73. printf("%c ",bt->data);
  74. InOrder(bt->rchild);
  75. }
  76. }
  77. // 后序遍历序列
  78. void PostOrder(BTNode *bt)
  79. {
  80. if (bt!=NULL)
  81. {
  82. PostOrder(bt->lchild);
  83. PostOrder(bt->rchild);
  84. printf("%c ",bt->data);
  85. }
  86. }
  87. // 层次遍历序列
  88. void LevelOrder(BTNode *b)
  89. {
  90. BTNode *p;
  91. BTNode *qu[MaxSize]; /*定义环形队列,存放结点指针*/
  92. int front,rear; /*定义队头和队尾指针*/
  93. front=rear=-1; /*置队列为空队列*/
  94. rear++;
  95. qu[rear]=b; /*根结点指针进入队列*/
  96. while (front!=rear) /*队列不为空*/
  97. { front=(front+1)%MaxSize;
  98. p=qu[front]; /*队头出队列*/
  99. printf("%c ",p->data); /*访问结点*/
  100. if (p->lchild!=NULL) /*有左孩子时将其进队*/
  101. { rear=(rear+1)%MaxSize;
  102. qu[rear]=p->lchild;
  103. }
  104. if (p->rchild!=NULL) /*有右孩子时将其进队*/
  105. { rear=(rear+1)%MaxSize;
  106. qu[rear]=p->rchild;
  107. }
  108. }
  109. }
  110. void main()
  111. {
  112. BTNode *bt;
  113. CreateBTree(bt,"A(B(D,E(G,H)),C(,F(I)))"); /*构造图5.10(a)所示的二叉树*/
  114. printf("二叉树bt:");DispBTree(bt);printf("\n");
  115. printf("先序遍历序列:");PreOrder(bt);printf("\n");
  116. printf("中序遍历序列:");InOrder(bt);printf("\n");
  117. printf("后序遍历序列:");PostOrder(bt);printf("\n");
  118. printf("层次遍历序列:");LevelOrder(bt);printf("\n");
  119. }