非递归中序遍历二叉树

╰半夏微凉° 2022-06-15 00:22 314阅读 0赞
  1. /*非递归中序遍历二叉树*/
  2. #include<stdio.h>
  3. #define maxsize 100
  4. typedef char datatype;
  5. /*二叉链表类型定义*/
  6. typedef struct Binnode
  7. {
  8. datatype data; /*数据域*/
  9. struct BinNode* lchild,*rchild; /*指向左、右孩子的指针*/
  10. }BinNode,*Bintree;
  11. /*顺序栈类型定义*/
  12. typedef struct
  13. {
  14. Bintree data[maxsize]; /*存储栈中数据元素*/
  15. int top; /*标志栈顶位置*/
  16. }SeqStk;
  17. /*初始化栈*/
  18. int InitStack(SeqStk *stk)
  19. {
  20. stk->top=0;
  21. return 1;
  22. }
  23. /*判栈空*/
  24. int EmptyStack(SeqStk *stk)
  25. {
  26. if(stk->top==0) /*若栈为空,则返回值1,否则返回0.*/
  27. return 1;
  28. else
  29. return 0;
  30. }
  31. /*入栈*/
  32. int Push(SeqStk *stk,Bintree x)
  33. {
  34. if(stk->top==maxsize-1) /*判断栈是否满*/
  35. {
  36. printf("栈满\n");
  37. return 0;
  38. }
  39. else
  40. {
  41. stk->top++; /*栈未满,top值加1.*/
  42. stk->data[stk->top]=x; /*元素x进栈*/
  43. return 1;
  44. }
  45. }
  46. /*出栈*/
  47. int Pop(SeqStk *stk)
  48. {
  49. if(EmptyStack(stk)) /*判断是否下溢(栈空)*/
  50. {
  51. printf("下溢\n");
  52. return 0;
  53. }
  54. else /*未下溢,栈顶元素出栈。*/
  55. {
  56. stk->top--; /*top值减1*/
  57. return 1;
  58. }
  59. }
  60. /*取栈顶数据元素,栈顶数据元素通过参数返回。*/
  61. Bintree GetTop(SeqStk *stk)
  62. {
  63. if(EmptyStack(stk))
  64. printf("栈空\n"); /*栈空,返回NULLData.*/
  65. else
  66. return stk->data[stk->top]; /*返回栈顶数据元素*/
  67. }
  68. /*按先序创建二叉树*/
  69. Bintree CreateTree(Bintree T)
  70. {
  71. datatype ch;
  72. scanf("%c",&ch);
  73. if(ch=='#')
  74. return NULL;
  75. else
  76. {
  77. T=(Bintree)malloc(sizeof(BinNode));
  78. T->data=ch;
  79. T->lchild=CreateTree(T->lchild);/*创建左子树*/
  80. T->rchild=CreateTree(T->rchild);/*创建右子树*/
  81. return T;
  82. }
  83. }
  84. /*非递归中序遍历二叉树*/
  85. void preorder(Bintree T)
  86. {
  87. Bintree p;
  88. SeqStk s;
  89. InitStack(&s);
  90. p=T;
  91. while(p || !EmptyStack(&s))
  92. {
  93. if(p)
  94. {
  95. Push(&s,p); /*当前结点指针入栈*/
  96. p=p->lchild; /*当前指针指向左孩子*/
  97. }
  98. else
  99. {
  100. p=GetTop(&s); /*栈顶元素退栈*/
  101. Pop(&s);
  102. printf("%c ",p->data); /*访问当前结点*/
  103. p=p->rchild; /*当前指针指向右孩子*/
  104. }
  105. }
  106. }
  107. main()
  108. {
  109. Bintree t;
  110. printf("请按先序的方式输入二叉树的结点元素(注:#表示节点为空):");
  111. t=CreateTree(t);
  112. printf("非递归中序遍历二叉树:");
  113. preorder(t);
  114. }

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读