86.png

    1. /*
    2. 写出在中序线索二叉树里查找指定节点在后序的前驱结点的算法
    3. 分析:
    4. 在后序序列中,若节点p有右子女,则右子女是其前驱,若无右子女而有左子女,则左子女是其前驱。若节点p左右子女均无,
    5. 设其中序左线索指向某祖先节点f(p是f右子树中按中序遍历的第一个节点),若f有左子女,则其左子女是节点p在后序中的前驱;
    6. 若f无左子女,则顺其前驱找双亲的双亲,一直找到双亲有左子女(此时左子女是p的前驱)。还有一种情况,若p是中序遍历的第
    7. 一个节点,则节点p在中序和后序下均没有前驱。
    8. */
    9. struct biTree {
    10. char data;
    11. struct biTree *lchild;
    12. struct biTree *rchild;
    13. int ltag, rtag;
    14. };
    15. #include <stdio.h>
    16. #include <stdlib.h>
    17. biTree *findPre(biTree *T,biTree *p) {//返回前驱结点
    18. struct biTree *f;
    19. if (p->rchild&&p->rtag==0) {//若该节点有右孩子,那么右子女是其前驱
    20. return p->rchild;
    21. }
    22. else if(p->ltag==0&&p->lchild) {//若该节点只有左子女则左子女是其前驱
    23. return p->lchild;
    24. }
    25. else {
    26. f = p->lchild;//此时左线索指向某祖先节点
    27. while (f&&f->ltag) {//如果该祖先节点没有左子女,继续找前驱
    28. f = f->lchild;
    29. }
    30. if (f) {
    31. return f->lchild;
    32. }
    33. else {
    34. return NULL;
    35. }
    36. }
    37. }
    38. int main() {
    39. struct biTree *T = (struct biTree *)malloc(sizeof(struct biTree));
    40. biTree *create(biTree *);
    41. T = create(T);
    42. void inThread(biTree *,biTree *);
    43. inThread(T,NULL);//中序遍历建立线索
    44. struct biTree *p = T->rchild->lchild,*pre=NULL;//手动指定一个节点
    45. pre=findPre(T,p);
    46. if (pre) {
    47. printf("节点p%c的前驱结点值为:%c",p->data,pre->data);
    48. }
    49. else {
    50. printf("节点p没有前驱结点");
    51. }
    52. return 0;
    53. }