树1 树的同构 C++实现
#题目
给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
输入格式:
输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数N (≤10),即该树的结点数(此时假设结点从0到N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。
输出格式:
如果两棵树是同构的,输出“Yes”,否则输出“No”。
输入样例1(对应图1):
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 -
输出样例1:
Yes
输入样例2(对应图2):
8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4
输出样例2:
No
#C++代码
#include<iostream>
using namespace std;
typedef struct Node Tree;
struct Node
{
char Data;
int Rchild;
int Lchild;
};
static Tree* tree1;
static Tree* tree2;
int Isomorphism(int t1, int t2)
{
if (t1 == -1 && t2 == -1) //各种情况下,判断左右子树和数据是否相同
return 1;
if (((t1 == -1) && (t2 != -1)) || ((t2 == -1) && (t1 != -1)))
return 0;
if (tree1[t1].Data != tree2[t2].Data)
return 0;
if (tree1[t1].Lchild == -1 && tree2[t2].Lchild == -1)
return Isomorphism(tree1[t1].Rchild, tree2[t2].Rchild);
if ((tree1[t1].Lchild != -1 && tree2[t2].Lchild != -1) && (tree1[tree1[t1].Lchild].Data == tree2[tree2[t2].Lchild].Data))
return (Isomorphism(tree1[t1].Lchild, tree2[t2].Lchild) && Isomorphism(tree1[t1].Rchild, tree2[t2].Rchild));
else return ( Isomorphism(tree1[t1].Rchild, tree2[t2].Lchild) && Isomorphism(tree1[t1].Lchild, tree2[t2].Rchild));
}
int main()
{
int n1 = 0, n2 = 0;
int* test1;
cin >> n1;
if (n1 > 0) //防止树为空
{
tree1 = new Tree[n1];
test1 = new int[n1] {0}; //用于确认树的根
}
char temp;
for (int i = 0; i < n1; i++) //将树1读入结构体数组中
{
cin >> tree1[i].Data;
cin >> temp;
if (temp == '-')
tree1[i].Lchild = -1;
else tree1[i].Lchild = temp - 48; //ASCII编码下,‘1’=49
cin >> temp;
if (temp == '-')
tree1[i].Rchild = -1;
else tree1[i].Rchild = temp - 48;
if (tree1[i].Lchild != -1)
test1[tree1[i].Lchild]++;
if (tree1[i].Rchild != -1)
test1[tree1[i].Rchild]++;
}
int i;
for (i = 0; i < n1; i++) //找到树的根
if (test1[i] == 0)
break;
int Root1 = i;
cin >> n2;
int* test2;
if (n2 > 0) //防止树为空
{
tree2 = new Tree[n2];
test2 = new int[n2] {0};
}
for (int i = 0; i < n2; i++) //将树2读入结构体数组中
{
cin >> tree2[i].Data;
cin >> temp;
if (temp == '-')
tree2[i].Lchild = -1;
else tree2[i].Lchild = temp - 48;
cin >> temp;
if (temp == '-')
tree2[i].Rchild = -1;
else tree2[i].Rchild = temp - 48;
if (tree2[i].Lchild != -1)
test2[tree2[i].Lchild]++;
if (tree2[i].Rchild != -1)
test2[tree2[i].Rchild]++;
}
for (i = 0; i < n2; i++)
if (test2[i] == 0)
break;
int Root2 = i;
if (n1 != n2) //如果树的长度不一,直接返回
{
cout << "No";
return 0;
}
if (n1 == 0)
{
cout << "Yes";
return 0;
}
if (Isomorphism(Root1, Root2) == 1)
cout << "Yes";
else cout << "No";
system("pause");
return 0;
}