#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
class TreeNode {
public:
ElementType element;
Tree left;
Tree right;
};
TreeNode t1[MaxTree], t2[MaxTree];
Tree BuildTree(TreeNode t[]);
int isomorphic(Tree root1, Tree root2);
using namespace std;
int main()
{
Tree root1, root2;
char *temp;
root1 = BuildTree(t1);
root2 = BuildTree(t2);
if (isomorphic(root1, root2)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
gets(temp);
return 0;
system("pause");
}
Tree BuildTree(TreeNode t[])
{
Tree root = -1;
char temp_left, temp_right;
int N, i;
cin >> N;
if (N) {
int check[MaxTree];
for (i = 0; i < N; i++) {
check[i] = 0;
}
for (i = 0; i < N; i++) {
cin >> t[i].element >> temp_left >> temp_right;
if (temp_left != '-') {
t[i].left = temp_left - '0';
check[t[i].left] = 1;
}
else {
t[i].left = Null;
}
if (temp_right != '-') {
t[i].right = temp_right - '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;
}
else return Null;
}
int isomorphic(Tree root1, Tree root2)
{
if ((root1 == Null) && (root2 == Null)) return 1;
if (((root1 == Null) && (root2 != Null)) || ((root1 != Null) && (root2 == Null))) return 0;
if (t1[root1].element != t2[root2].element) return 0;
if ((t1[root1].left == Null) && (t2[root2].left == Null)) return isomorphic(t1[root1].right, t2[root2].right);
if ((t1[root1].left != Null) && (t2[root2].left != Null) && (t1[t1[root1].left].element == t2[t2[root2].left].element)) {
return (isomorphic(t1[root1].left, t2[root2].left) && isomorphic(t1[root1].right, t2[root2].right));
}
else {
return (isomorphic(t1[root1].left, t2[root2].right) && isomorphic(t1[root1].right, t2[root2].left));
}
}
PTA数据结构与算法题目集(中文)7-3 树的同构 (25 分)
最新推荐文章于 2021-07-11 15:14:33 发布