81.png

    1. /*
    2. 试给出二叉树的自下而上、从右到左的层次遍历算法
    3. 分析:
    4. 我们只需要在层次遍历的基础上加入栈的使用,我们每次出队后的数据将其入栈,队列空了时,再去依次访问栈中元素,即可达到要求
    5. */
    6. struct biTree {
    7. char data;
    8. struct biTree *lchild;
    9. struct biTree *rchild;
    10. };
    11. struct Squeue {
    12. biTree *arr;
    13. int front, rear;
    14. };
    15. struct Stack {
    16. biTree *arr;
    17. int len;
    18. int top;
    19. };
    20. #include <stdio.h>
    21. #include <stdlib.h>
    22. void levelOrder2(biTree *T, Squeue *sq, int maxSize) {
    23. struct Stack *s = (struct Stack *)malloc(sizeof(struct Stack));
    24. struct biTree *p = T;
    25. struct biTree *r = (struct biTree *)malloc(sizeof(struct biTree));
    26. bool enQueue(Squeue *, biTree *, int);
    27. bool isEmpty(Squeue *);
    28. bool deQueue(Squeue *, biTree **, int);
    29. Stack *createStack(int);
    30. bool push(Stack *,biTree *);
    31. bool empty(Stack *);
    32. biTree *top(Stack *);
    33. bool pop(Stack *);
    34. s = createStack(maxSize);
    35. enQueue(sq, p, maxSize);
    36. while (!isEmpty(sq)) {
    37. deQueue(sq, &r, maxSize);
    38. push(s,r);
    39. if (r->lchild)enQueue(sq, r->lchild, maxSize);
    40. if (r->rchild)enQueue(sq, r->rchild, maxSize);
    41. }
    42. while (!empty(s)) {
    43. r = top(s);
    44. printf("%c ",r->data);
    45. pop(s);
    46. }
    47. }
    48. int main() {
    49. int count = 0;
    50. struct biTree *T = (struct biTree *)malloc(sizeof(struct biTree));
    51. struct Squeue *sq = (struct Squeue *)malloc(sizeof(struct Squeue));
    52. biTree *create(biTree *);
    53. void nodeNum(biTree *, int *);
    54. Squeue *createQueue(int);
    55. T = create(T);//创建一颗二叉树
    56. nodeNum(T, &count);//统计二叉树节点个数
    57. sq = createQueue(count);
    58. levelOrder2(T, sq, count);
    59. return 0;
    60. }