#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode
{
ElementType Data;
Tree Left;
Tree Right;
}T1[MaxTree], T2[MaxTree];
int main()
{
Tree R1, R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
if (Isomorphic(R1, R2)) printf("Yes\n");
else printf("No\n");
system("pause");
return 0;
}
Tree BuildTree(struct TreeNode T[])
{
int N;
scanf("%d", &N);
if (N == 0)
return Null;
getchar();
int check[MaxTree]={0};
int i = 0;
char cl, cr;
for (i = 0; i < N; i++)
{
//cl 跟 cr 输入的是指向左右的下标
scanf("%c %c %c", &T[i].Data, &cl, &cr);
getchar();
if (cl != '-')
{
T[i].Left = cl - '0';
check[T[i].Left] = 1;
}
else
{
T[i].Left = Null;
}
if (cr != '-')
{
T[i].Right = cr - '0';
check[T[i].Right] = 1;
}
else
{
T[i].Right = Null;
}
}
for (i = 0; i < N; i++)
{
if (check[i] == 0)break;
}
//返回根
return i;
}
int Isomorphic(Tree R1, Tree R2)
{
if (R1 == Null && R2 == Null)return 1;
if ((R1 == Null && R2 != Null) || (R1 != Null && R2 == Null))return 0;
if (T1[R1].Data != T2[R2].Data)return 0;
if (T1[R1].Left == Null && T2[R2].Left == Null)return Isomorphic(T1[R1].Right, T2[R2].Right);
if (T1[R1].Right == Null && T2[R2].Right == Null)return Isomorphic(T1[R1].Left, T2[R2].Left);
if ((T1[R1].Left != Null && T2[R2].Left != Null) && (T1[T1[R1].Left].Data == T2[T2[R2].Left].Data))
return Isomorphic(T1[R1].Left, T2[R2].Left) && Isomorphic(T1[R1].Right, T2[R2].Right);
else
return Isomorphic(T1[R1].Right, T2[R2].Left) && Isomorphic(T1[R1].Left, T2[R2].Right);
}
树的同构(顺序存储结构)
最新推荐文章于 2021-01-09 20:56:04 发布