思路:基本参照慕课上的浙大数据结构思路来,判断同构的函数处做了一些小修改
代码如下
#include <iostream>
using namespace std;
typedef struct tree{
char ch;
int Left, Right;
}Tree;
Tree T1[10], T2[10];
int CreatTree(Tree T[]);
bool Isomorphic(int r1, int r2);
int main() {
int R1, R2;
R1 = CreatTree(T1);
R2 = CreatTree(T2);
if(Isomorphic(R1, R2)) printf("Yes");
else printf("No");
}
int CreatTree(Tree T[]) {
int N; scanf("%d\n", &N);
int check[10] = {0};
int Root = -1; //表示根节点下标
for(int i = 0; i < N; i++) {
char cl, cr;
scanf("%c %c %c\n", &T[i].ch, &cl, &cr);
if('-' == cl) T[i].Left = -1;
else {
T[i].Left = cl-'0';
check[T[i].Left] = 1;
}
if('-' == cr) T[i].Right = -1;
else {
T[i].Right = cr-'0';
check[T[i].Right] = 1;
}
}
for(int i = 0; i < N; i++)
if(0 == check[i]) {Root = i; break;}
return Root;
}
bool Isomorphic(int R1, int R2) {
if(-1 == R1 && -1 == R2) return true; //都是空树,同构
else if((-1 == R1)&&(-1 != R2) || (-1 == R2)&&(-1 != R1) || (T1[R1].ch != T2[R2].ch))
return false; //只有一棵树空或者根不同,不同构
else if(-1 == T1[R1].Left && -1 == T2[R2].Left) //都没有左子树,只需比较右子树
return Isomorphic(T1[R1].Right, T2[R2].Right);
else if(-1 == T1[R1].Right && -1 == T2[R2].Right) //都没有右子树,只需比较左子树
return Isomorphic(T1[R1].Left, T2[R2].Left);
else if(T1[T1[R1].Left].ch == T2[T2[R2].Left].ch) //左子树数据相同,即不需要交换左右子树,递归判断左右子树是否同构
return Isomorphic(T1[R1].Left, T1[R2].Left) && Isomorphic(T1[R1].Right, T1[R2].Right);
else //需要交换左右子树再判断是否同构
return Isomorphic(T1[R1].Left, T2[R2].Right) && Isomorphic(T1[R1].Right, T2[R2].Left);
}
反馈:
- scanf读入字符时,空格和\n可以直接代替输入中的空格与回车,无需添加getchar()读走空白字符