87.png

    1. /*
    2. 假设二叉树是用二叉链表存储,试设计一个算法,求先序遍历中第k(1<=k<=二叉树的节点个数)个节点的值
    3. 分析:
    4. 很简单,每遍历一个节点,计数器便加一,直至等于k
    5. */
    6. struct biTree {
    7. char data;
    8. struct biTree *lchild;
    9. struct biTree *rchild;
    10. };
    11. #define _CRT_SECURE_NO_WARNINGS
    12. #include <stdio.h>
    13. #include <stdlib.h>
    14. biTree *preK(biTree *T, int k) {
    15. static int num = 0;
    16. static biTree *r;
    17. if (!T) return NULL;
    18. if (++num == k) {//找到后,记录下来
    19. r = T;
    20. }
    21. else {
    22. preK(T->lchild, k);
    23. preK(T->rchild, k);
    24. }
    25. return r;
    26. }
    27. int main() {
    28. int k, count = 0;
    29. struct biTree *T = (struct biTree*)malloc(sizeof(struct biTree));
    30. T->lchild = NULL;
    31. T->rchild = NULL;
    32. T->data = NULL;
    33. struct biTree *r;
    34. biTree *create(biTree *);
    35. void inOrder(biTree *);
    36. void nodeNum(biTree *, int *);
    37. T = create(T);//创建一颗二叉树
    38. nodeNum(T, &count);
    39. if (!count) {
    40. printf("该二叉树是空树");
    41. }
    42. else {
    43. printf("请输入要寻找的k值(1<=k<=%d):k=", count);
    44. scanf("%d", &k);
    45. while (k<1 || k>count) {
    46. printf("输入有误,请重输 k=");
    47. scanf("%d", &k);
    48. }
    49. r = preK(T, k);
    50. printf("第%d个节点值为%c", k, r->data);
    51. }
    52. return 0;
    53. }