84.png

    1. /*
    2. 设计一个算法将二叉树的叶节点按从左到右的顺序连成一个单链表,表头指针为head。二叉树按二叉链表方式存储,连接时用叶节点的
    3. 右指针来存放单链表指针。
    4. 分析:
    5. 我们要将叶节点连起来,那么我们首先要按从左至右的顺序找出叶节点,要满足这样的出场顺序,可以采用先序,中序,后序,
    6. 这里我们采用中序遍历。
    7. */
    8. struct biTree {
    9. char data;
    10. struct biTree *lchild;
    11. struct biTree *rchild;
    12. };
    13. struct Stack {
    14. biTree *arr;
    15. int len;
    16. int top;
    17. };
    18. #include <stdio.h>
    19. #include <stdlib.h>
    20. struct biTree *h = (struct biTree *)malloc(sizeof(struct biTree));//创建一个头结点
    21. struct biTree *pre = h;
    22. biTree *leafLink(biTree *b) {//将二叉树b中的所有叶子结点连起来
    23. if (b) {
    24. leafLink(b->lchild);//中序遍历左子树
    25. if (!b->lchild && !b->rchild) {//叶节点
    26. pre->rchild = b;
    27. pre = b;
    28. }
    29. leafLink(b->rchild);//中序遍历右子树
    30. pre->rchild = NULL;//设置链表尾
    31. }
    32. return h;
    33. }
    34. int main() {
    35. struct biTree *b = (struct biTree *)malloc(sizeof(struct biTree ));
    36. biTree *create(biTree *);
    37. b = create(b);//创建一颗二叉树
    38. leafLink(b);
    39. while (h->rchild) {
    40. printf("%c ", h->rchild->data);
    41. h = h->rchild;
    42. }
    43. return 0;
    44. }