如何实现判断两个二叉树是否相同?

作者站长头像
站长
· 阅读数 9
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define OK 1
#define OVERFLOW -1

typedef int Status;
typedef char TElemType;

typedef struct BiTNode {
    TElemType data;
    struct BiTNode *lChild, *rChild;
} BiTNode, *BiTree;

Status InitBiTree(BiTree *BT);

Status CreateBiTree(BiTree *BT);

bool IsSame(BiTree BT1, BiTree BT2);

Status main() {
    BiTree BT1, BT2;
    printf("To Creat Binary Tree 1,Please Input PreOrder with '#':\n");
    InitBiTree(&BT1);
    CreateBiTree(&BT1);
    printf("To Creat Binary Tree 2,Please Input PreOrder with '#':\n");
    InitBiTree(&BT2);
    CreateBiTree(&BT2);
    if (IsSame(BT1, BT2)) {
        printf("\n相同\n");
    } else {
        printf("\n不相同\n");
    }
    return OK;
}

Status InitBiTree(BiTree *BT) {
    *BT = NULL;
    return OK;
}

Status CreateBiTree(BiTree *BT) {
    TElemType ch;
    scanf("%c", &ch);
    if (ch == '#') {
        *BT = NULL;
    } else {
        *BT = (BiTNode *) malloc(sizeof(BiTNode));
        if (!(*BT)) {
            exit(OVERFLOW);
        }
        (*BT)->data = ch;
        CreateBiTree(&(*BT)->lChild);
        CreateBiTree(&(*BT)->rChild);
    }
    return OK;
}

bool IsSame(BiTree BT1, BiTree BT2) {
    if (BT1 == NULL && BT2 == NULL) {
        return true;
    }
    if (BT1 == NULL || BT2 == NULL) {
        return false;
    }
    if (BT1->data != BT2->data) {
        return false;
    }
    return (IsSame(BT1->lChild, BT2->lChild) && IsSame(BT1->rChild, BT2->rChild));
}

在如下输入的情况下,这段代码运行输出不出预期的结果“相同”。

To Creat Binary Tree 1,Please Input PreOrder with '#':
ab#d##c##
To Creat Binary Tree 2,Please Input PreOrder with '#':
ab#d##c##

如何实现判断两个二叉树是否相同?

回复
1个回答
avatar
test
2024-07-14

在你调用 CreateBiTree(&BT2) 里面的 scanf 会获得第一次输入行尾的回车,但你的程序没处理这种情况,就直接卡死等待了,把 scanf 那里改一下就好了

    do
    {
        scanf("%c", &ch);
    } while (ch == '\n');
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容