7-3 树的同构 (25分)
给定两棵树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
//
// Created by TIGA_HUANG on 2020/9/24.
//
#include <iostream>
#include <sstream>
using namespace std;
struct node {
string data;
int left;
int right;
int father;
} a[20], b[20];
int s2i(string &str) {
int ret;
stringstream ss;
ss << str;
ss >> ret;
return ret;
}
bool dfs(int t1, int t2) {
if (t1 == -1 && t2 == -1)
return true;
if (t1 == -1 || t2 == -1)
return false;
if (a[t1].data == b[t2].data) {
if (a[t1].left == -1 && b[t2].left == -1)
return dfs(a[t1].right, b[t2].right);
else if (a[t1].right == -1 && b[t2].right == -1)
return dfs(a[t1].left, b[t2].left);
if (a[t1].right != -1 && b[t1].right != -1 && a[a[t1].left].data == a[b[t2].left].data)
return dfs(a[t1].left, b[t2].left) && dfs(a[t1].right, b[t2].right);
else
return dfs(a[t1].left, b[t2].right) && dfs(a[t1].right, b[t2].left);
} else
return false;
}
void checkA(int t) {
if (t == -1)
return;
cout << a[t].data << ' ';
if (a[t].left != -1)
checkA(a[t].left);
if (a[t].right != -1)
checkA(a[t].right);
}
void checkB(int t) {
if (t == -1)
return;
cout << b[t].data << ' ';
if (b[t].left != -1)
checkB(b[t].left);
if (b[t].right != -1)
checkB(b[t].right);
}
int main() {
int N;
cin >> N;
string data, left_str, right_str;
int left, right, root_a = -1, root_b = -1;
for (int i = 0; i < N; ++i) {
a[i].father = -1;
}
for (int i = 0; i < N; ++i) {
cin >> data >> left_str >> right_str;
if (left_str == "-")
left = -1;
else
left = s2i(left_str);
if (right_str == "-")
right = -1;
else
right = s2i(right_str);
a[i] = {data, left, right, a[i].father};
if (left != -1)
a[left].father = i;
if (right != -1)
a[right].father = i;
}
for (int i = 0; i < N; ++i) {
if (a[i].father == -1) {
root_a = i;
break;
}
}
cin >> N;
for (int i = 0; i < N; ++i) {
b[i].father = -1;
}
for (int i = 0; i < N; ++i) {
cin >> data >> left_str >> right_str;
if (left_str == "-")
left = -1;
else
left = s2i(left_str);
if (right_str == "-")
right = -1;
else
right = s2i(right_str);
b[i] = {data, left, right, b[i].father};
b[left].father = i;
b[right].father = i;
if (left != -1)
b[left].father = i;
if (right != -1)
b[right].father = i;
}
for (int i = 0; i < N; ++i) {
if (b[i].father == -1) {
root_b = i;
break;
}
}
// checkB(root_b);
// cout << endl;
// cout << root_a << ' ' << root_b;
if (dfs(root_a, root_b))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}