1. /*
    2. 试写出层次遍历的算法
    3. 分析:
    4. 正如名字所表现的那样,要一层一层的遍历,这里我们就需要用到队列这种数据结构了,具体做法是:
    5. 先将根节点入队,然后根节点出队,并依次将根节点的左孩子、右孩子入队。后续如此循环,直至队空
    6. */
    7. struct biTree {
    8. char data;
    9. struct biTree *lchild;
    10. struct biTree *rchild;
    11. };
    12. struct Squeue {
    13. biTree *arr;
    14. int front, rear;
    15. };
    16. #include <stdio.h>
    17. #include <stdlib.h>
    18. void levelOrder(biTree *T,Squeue *sq,int maxSize) {
    19. struct biTree *p = T;
    20. struct biTree *r = (struct biTree *)malloc(sizeof(struct biTree));
    21. bool enQueueS(Squeue *, biTree *, int);
    22. bool isEmpty(Squeue *);
    23. bool deQueueS(Squeue *, biTree *,int);
    24. enQueueS(sq,p,maxSize);
    25. while (!isEmpty(sq)) {
    26. deQueueS(sq,r,maxSize);
    27. printf("%c ",r->data);
    28. if(r->lchild)enQueueS(sq, r->lchild, maxSize);
    29. if (r->rchild)enQueueS(sq, r->rchild, maxSize);
    30. }
    31. }
    32. int main() {
    33. int count = 0;
    34. struct biTree *T = (struct biTree *)malloc(sizeof(struct biTree));
    35. struct Squeue *sq = (struct Squeue *)malloc(sizeof(struct Squeue));
    36. biTree *create(biTree *);
    37. void nodeNum(biTree *,int *);
    38. Squeue *createQueue(int);
    39. T = create(T);//创建一颗二叉树
    40. nodeNum(T,&count);//统计二叉树节点个数
    41. sq = createQueue(count);
    42. levelOrder(T,sq,count);
    43. return 0;
    44. }