1.二叉树中序非递归实现

    1. #include<stdio.h>
    2. #include<stdlib.h>
    3. #define MaxSize 100
    4. typedef struct TreeNode * ElementType;
    5. typedef struct SNode *Stack;
    6. struct TreeNode
    7. {
    8. int Data;
    9. struct TreeNode *Left;
    10. struct TreeNode *Right;
    11. };
    12. struct SNode
    13. {
    14. ElementType Data[MaxSize];
    15. int Top;
    16. };
    17. Stack S;
    18. struct TreeNode * CreateBinTree(void);
    19. Stack CreateStack();
    20. bool IsFull(Stack S);
    21. bool IsEmpty(Stack S);
    22. void Push(Stack S,ElementType item);
    23. ElementType Pop(Stack S);
    24. void InOrderTraversal(struct TreeNode * BT);
    25. int main(void)
    26. {
    27. struct TreeNode *pT = CreateBinTree();
    28. printf("二叉树非递归遍历:\n");
    29. InOrderTraversal(pT);
    30. free(pT);
    31. return 0;
    32. }
    33. struct TreeNode * CreateBinTree(void)
    34. {
    35. struct TreeNode *pA = (struct TreeNode *)malloc(sizeof(TreeNode));
    36. struct TreeNode *pB = (struct TreeNode *)malloc(sizeof(TreeNode));
    37. struct TreeNode *pC = (struct TreeNode *)malloc(sizeof(TreeNode));
    38. struct TreeNode *pD = (struct TreeNode *)malloc(sizeof(TreeNode));
    39. struct TreeNode *pE = (struct TreeNode *)malloc(sizeof(TreeNode));
    40. pA->Data = 5;
    41. pB->Data = 6;
    42. pC->Data = 7;
    43. pD->Data = 8;
    44. pE->Data = 9;
    45. pA->Left = pB;
    46. pA->Right = pC;
    47. pB->Left = NULL;
    48. pB->Right = NULL;
    49. pC->Left = pD;
    50. pC->Right = NULL;
    51. pD->Left = NULL;
    52. pD->Right = pE;
    53. pE->Left = NULL;
    54. pE->Right = NULL;
    55. return pA;
    56. }
    57. Stack CreateStack()
    58. {
    59. S = (Stack)malloc(sizeof(struct SNode));
    60. S->Top = -1;
    61. return S;
    62. }
    63. bool IsFull(Stack S)
    64. {
    65. return (S->Top == MaxSize-1);
    66. }
    67. bool IsEmpty(Stack S)
    68. {
    69. return (S->Top == -1);
    70. }
    71. void Push(Stack S,ElementType item)
    72. {
    73. if(IsFull(S))
    74. {
    75. printf("堆栈满");
    76. return;
    77. }else
    78. {
    79. S->Top++;
    80. S->Data[S->Top] = item;
    81. return;
    82. }
    83. }
    84. ElementType Pop(Stack S)
    85. {
    86. if(IsEmpty(S))
    87. {
    88. printf("堆栈空");
    89. return NULL;
    90. }
    91. else
    92. {
    93. ElementType val = S->Data[S->Top];
    94. S->Top--;
    95. return val;
    96. }
    97. }
    98. void InOrderTraversal(struct TreeNode * BT)
    99. {
    100. struct TreeNode * T = BT;
    101. Stack S = CreateStack();
    102. while(T || !IsEmpty(S))
    103. {
    104. while(T)
    105. {
    106. Push(S,T);
    107. T = T->Left;
    108. }
    109. if(!IsEmpty(S))
    110. {
    111. T = Pop(S);
    112. printf("%d\n", T->Data);
    113. T = T->Right;
    114. }
    115. }
    116. }

    2.KMP算法