82.png

    1. /*
    2. 假设二叉树采用二叉链表存储结构,设计一个算法,求非空二叉树的宽度(即具有节点数最多的那一层的节点个数)
    3. 分析:
    4. 这道题和求高度那道题大同小异。我们仍然可以采取层次遍历,统计每一层的节点个数,找到宽度最大的那一层。
    5. */
    6. struct biTree {
    7. char data;
    8. struct biTree *lchild;
    9. struct biTree *rchild;
    10. };
    11. struct LinkQueue {//上次求高度采用的是顺序队列,这次采用链式队列,雨露均沾哈哈
    12. struct Link *front, *rear;
    13. };
    14. #include <stdio.h>
    15. #include <stdlib.h>
    16. int getWidth(biTree *b, LinkQueue *lq) {
    17. int oldNum = 0, curNum = 0, width = 0;;
    18. bool enQueue(LinkQueue *lq, biTree *node);
    19. bool deQueue(LinkQueue *lq, biTree **node);
    20. bool isEmpty(LinkQueue *lq);
    21. struct biTree *p = b;
    22. struct biTree *r=(struct biTree*)malloc(sizeof(struct biTree));
    23. if (p) {
    24. enQueue(lq, p);//入队
    25. oldNum++;
    26. width = 1;
    27. while (!isEmpty(lq)) {
    28. while (oldNum--) {
    29. deQueue(lq, &r);//队首元素出队
    30. if (r->lchild) {//若有左孩子,将左孩子入队
    31. enQueue(lq, r->lchild);
    32. curNum++;//当前队列元素加1
    33. }
    34. if (r->rchild) {//若有右孩子,将右孩子入队
    35. enQueue(lq, r->rchild);
    36. curNum++;//当前队列元素加1
    37. }
    38. }
    39. curNum > width ? width = curNum : NULL;//如果当前队列元素多于之前的,宽度变更
    40. oldNum = curNum;//继续进行操作
    41. curNum = 0;
    42. }
    43. }
    44. return width;
    45. }
    46. int main() {
    47. struct biTree *b = (struct biTree*)malloc(sizeof(struct biTree));
    48. struct LinkQueue *lq;
    49. biTree *create(biTree *);
    50. b = create(b);//创建一颗二叉树
    51. LinkQueue *create();
    52. lq = create();//创建链式队列
    53. printf("该二叉树的宽度为:%d",getWidth(b, lq));
    54. return 0;
    55. }