#include<stdio.h>
#include<stdlib.h>
/*
8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -
*/
// 二叉树的存储结构:结构数组,也叫静态链表
#define ElementType char
#define MaxSize 10
#define Tree int
#define Null -1
struct TreeNode {
ElementType Data;
Tree Left;
Tree Right;
} Tree1[MaxSize], Tree2[MaxSize];
// 建立二叉树
Tree BuildTree(struct TreeNode T[]) {
int N, i;
char cl, cr;
Tree Root = -1;
scanf("%d\n", &N);
int *check = (int*)malloc(N*sizeof(int));
if (N) {
for (i = 0; i < N; i++) check[i] = 0;
for (i = 0; i < N; i++) {
scanf("\n%c %c %c\n", &T[i].Data, &cl, &cr);
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]) break;
}
Root = i;
}
return Root;
}
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 (Tree1[R1].Data != Tree2[R2].Data) return 0;
if (Tree1[R1].Left == Null && Tree2[R2].Left == Null)
Isomorphic(Tree1[R1].Right, Tree2[R2].Right);
if (Tree1[R1].Right == Null && Tree2[R2].Right == Null)
Isomorphic(Tree1[R1].Left, Tree2[R2].Left);
if ((Tree1[R1].Left != Null && Tree2[R2].Left != Null) && (Tree1[Tree1[R1].Left].Data == Tree2[Tree2[R1].Left].Data))
return Isomorphic(Tree1[R1].Left, Tree2[R2].Left) && Isomorphic(Tree1[R1].Right, Tree2[R2].Right);
else
return Isomorphic(Tree1[R1].Left, Tree2[R2].Right) && Isomorphic(Tree1[R1].Left, Tree2[R2].Right);
}
int main() {
Tree tree1, tree2;
tree1 = BuildTree(Tree1);
tree2 = BuildTree(Tree2);
if (Isomorphic(tree1, tree2))
printf("YES!\n");
else
printf("NO!\n");
return 0;
}
实例3-1 树的同构
最新推荐文章于 2021-06-14 19:07:53 发布