#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct treenode
{
char alpha;
int left, right;
};
struct treenode tree1[11], tree2[11];
bool iscon(int x, int y)
{
if (x == -1 && y == -1)
return true;
if (x == -1 || y == -1)
return false;
if (tree1[x].alpha != tree2[y].alpha)
return false;
if (tree1[x].left == -1 && tree2[y].left == -1)
return iscon(tree1[x].right, tree2[y].right);
if (tree1[x].right == -1 && tree2[y].right == -1)
return iscon(tree1[x].left, tree2[y].left);
if (tree1[tree1[x].left].alpha == tree2[tree2[y].left].alpha)
return iscon(tree1[x].left, tree2[y].left) && iscon(tree1[x].right, tree2[y].right);
return iscon(tree1[x].left, tree2[y].right) && iscon(tree1[x].right, tree2[y].left);
}
int main(int argc, char **argv)
{
bool book1[12] = {false}, book2[12] = {false};
int cnt, inport1 = -1, inport2 = -1;
scanf("%d", &cnt);
if (cnt)
{
for (int i = 0; i < cnt; i++)
{
char ch1, ch2, ch3;
scanf("%*c%c %c %c", &ch1, &ch2, &ch3);
tree1[i].alpha = ch1;
if (ch2 != '-')
{
tree1[i].left = ch2 - '0';
book1[ch2 - '0'] = true;
}
else
tree1[i].left = -1;
if (ch3 != '-')
{
tree1[i].right = ch3 - '0';
book1[ch3 - '0'] = true;
}
else
tree1[i].right = -1;
}
for (int i = 0; i < cnt; i++)
if (!book1[i])
{
inport1 = i;
break;
}
}
scanf("%d", &cnt);
if (cnt)
{
for (int i = 0; i < cnt; i++)
{
char ch1, ch2, ch3;
scanf("%*c%c %c %c", &ch1, &ch2, &ch3);
tree2[i].alpha = ch1;
if (ch2 != '-')
{
tree2[i].left = ch2 - '0';
book2[ch2 - '0'] = true;
}
else
tree2[i].left = -1;
if (ch3 != '-')
{
tree2[i].right = ch3 - '0';
book2[ch3 - '0'] = true;
}
else
tree2[i].right = -1;
}
for (int i = 0; i < cnt; i++)
if (!book2[i])
{
inport2 = i;
break;
}
}
if (iscon(inport1, inport2))
printf("Yes\n");
else
printf("No\n");
return EXIT_SUCCESS;
}
数组下标法,建立两棵二叉树并找到它们的根节点。
递归遍历两颗二叉树是否满足题目中所说的“同构”
1.两棵树的对应节点两个儿子相同 ;2.其中一棵树左右儿子交换后相同
两棵树所有节点满足上面两个条件时树同构。