85.png

    1. /*
    2. 试设计判断两课二叉树是否相似的算法。所谓二叉树T1和T2相似,指的是T1和T2都是空的二叉树或只有一个根节点;或二者左子树相似
    3. 且左子树相似
    4. 分析:
    5. 典型的要采取递归来处理
    6. */
    7. struct biTree {
    8. char data;
    9. struct biTree *lchild;
    10. struct biTree *rchild;
    11. };
    12. #include <stdlib.h>
    13. #include <stdio.h>
    14. bool isSimilar(biTree *T1, biTree *T2) {
    15. if (!T1 && !T2) {//T1,T2都是空的二叉树
    16. return true;
    17. }
    18. else if (!T1 || !T2) {//T1,T2只有一个为空,则不相似
    19. return false;
    20. }
    21. else {
    22. if (isSimilar(T1->lchild, T2->lchild) && isSimilar(T1->rchild, T2->rchild))//左右子树均相似,才相似
    23. return true;
    24. else
    25. return false;
    26. }
    27. }
    28. int main() {
    29. struct biTree *T1 = (struct biTree *)malloc(sizeof(struct biTree));
    30. struct biTree *T2 = (struct biTree *)malloc(sizeof(struct biTree));
    31. biTree *create(biTree *);
    32. printf("第一棵树数据:\n");
    33. T1 = create(T1);
    34. printf("\n");
    35. printf("第二棵树数据:\n");
    36. T2 = create(T2);
    37. isSimilar(T1, T2) ? printf("相似") : printf("不相似");
    38. return 0;
    39. }