给定两棵树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
#include <iostream>
using namespace std;
using Tree_ = class TreeNode;
using Tree = Tree_*;
class TreeNode {
public:
char Data{ '0' };
int Left{ '0' };
int Right{ '0' };
int Test{0};
};
int CreateTree(Tree& T, int N) {
for (int i = 0; i < N; i++) {
char left, right;
cin >> T[i].Data >> left >> right;
if (left != '-') {
T[i].Left = (left - '0');
T[T[i].Left].Test = 1;
}
else {
T[i].Left = -1;
}
if (right != '-') {
T[i].Right = (right - '0');
T[T[i].Right].Test = 1;
}
else {
T[i].Right = -1;
}
}
for (int i = 0; i < N; i++) {
if (T[i].Test == 0) {
return i;
}
}
};
bool Isomorphism(Tree T1, int t1, Tree T2, int t2) {
if (T1[t1].Left == -1 && T1[t1].Right == -1 && T2[t2].Left == -1 && T2[t2].Right == -1) {
return T1[t1].Data == T2[t2].Data;
}//两棵树都没有子树的情况;
else if (T1[t1].Left == -1 && T1[t1].Right == -1 && (T2[t2].Left != -1 || T2[t2].Right != -1)) {
return false;
}//树1空,树2不空的情况;
else if (T2[t2].Left == -1 && T2[t2].Right == -1 && (T1[t1].Left != -1 || T1[t1].Right != -1)) {
return false;
}//树2空,树1不空的情况;
else if (T1[t1].Left == -1 && T2[t2].Left == -1) {
return Isomorphism(T1, T1[t1].Right, T2, T2[t2].Right);
}//树1和树2的左子树为空的情况下,判断右子树;
else if (T1[t1].Right == -1 && T2[t2].Right == -1) {
return Isomorphism(T1, T1[t1].Left, T2, T2[t2].Left);
}//树1和树2的右子树为空的情况下,判断左子树;
else if (T1[t1].Left == -1 && T2[t2].Right == -1) {
return Isomorphism(T1, T1[t1].Right, T2, T2[t2].Left);
}//树1左子树空,树2右子树空, 判断树1的右子树和树2的左子树;
else if (T2[t2].Left == -1 && T1[t1].Right == -1) {
return Isomorphism(T2, T2[t2].Right, T1, T1[t1].Left);
}//树2左子树空,树1右子树空, 判断树2的右子树和树1的左子树;
else {
return (Isomorphism(T1, T1[t1].Left, T2, T2[t2].Left) && Isomorphism(T1, T1[t1].Right, T2, T2[t2].Right))
|| (Isomorphism(T1, T1[t1].Left, T2, T2[t2].Right) && Isomorphism(T1, T1[t1].Right, T2, T2[t2].Left));
}//判断树1左子树和树2左子树同构 并且 判断树1右子树和树2右子树同构 的情况
//或者树1左子树和树2右子树同构 并且 判断树1右子树和树2左子树同构 的情况
//两种情况满足一种即可判定为同构。
};
int main() {
int N1,N2;
int root1{0}, root2{0};
Tree T1 = nullptr;
Tree T2 = nullptr;
cin >> N1;
if (N1 != 0) {
T1 = new Tree_[N1];
root1 = CreateTree(T1, N1);
}
cin >> N2;
if (N2 != 0) {
T2 = new Tree_[N2];
root2 = CreateTree(T2, N2);
}
if (N1 == 0 && N2 == 0) {
cout << "Yes" << endl;
}//两棵空树;
else if (N1 != N2) {
cout << "No" << endl;
}//其中一个树为空,另一个非空;
else if (Isomorphism(T1, root1, T2, root2) == true) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}