# 03-树1 树的同构

149人阅读 评论(0)

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 -

Yes

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

No

1.AB都空，y
2.AB其中一个不空，n
3.AB的数据不相等，n
4.A树的左孩子B树的左孩子空，return 判断A树的右孩子和B树的右孩子
5.一个空一个不空，return A左与B右&&A右与B左
6.A树的左孩子B树的左孩子不空，return A左与B左&&A右与B右

#include <iostream>

using namespace std;

#define Elementtype char

typedef struct bitnode
{
Elementtype data;
char left;
char right;
}bitnode;

int findtop(int *findtop, int num)
{
for (int i = 0; i < num; i++)
{
if (findtop[i] != 1)
return i;
}
}

bitnode* tree_1;
bitnode* tree_2;

int travel(int t1, int t2)
{

if (t1 == -1 && t2 == -1)
return 1;
if ((t1 != -1 && t2 == -1) || (t1 == -1 && t2 != -1))
return 0;
if (tree_1[t1].data != tree_2[t2].data)
return 0;
if ((tree_1[t1].left == -1) && (tree_2[t2].left == -1))
return travel(tree_1[t1].right, tree_2[t2].right);
if (tree_1[tree_1[t1].left].data == tree_2[tree_2[t2].left].data)
return (travel(tree_1[t1].left, tree_2[t2].left) && travel(tree_1[t1].right, tree_2[t2].right));
else
return (travel(tree_1[t1].left, tree_2[t2].right) && travel(tree_1[t1].right, tree_2[t2].left));

}

void input()
{
int treenum_1 = 0, treenum_2 = 0;

cin >> treenum_1;
tree_1 = new bitnode[treenum_1];
int *findtree_1top = new int[treenum_1];

char temp1;
char temp2;
for (int i = 0; i < treenum_1; i++)
{
cin >> (tree_1 + i)->data;
cin >> temp1;
cin >> temp2;

if (temp1 == '-')
(tree_1 + i)->left = -1;
else
{
(tree_1 + i)->left = (temp1 - '0');
findtree_1top[temp1 - '0'] = 1;
//cout << (int)(tree_1 + i)->left << ' ';
}

if (temp2 == '-')
(tree_1 + i)->right = -1;
else
{
(tree_1 + i)->right = (temp2 - '0');
findtree_1top[temp2 - '0'] = 1;
//cout << (int)(tree_1 + i)->right << ' ';
}

}

cin >> treenum_2;
int *findtree_2top = new int[treenum_2];
if (treenum_1 == treenum_2)
{
if (treenum_1 == 0)
{
cout << "Yes";
}
else
{
tree_2 = new bitnode[treenum_2];

for (int i = 0; i < treenum_2; i++)
{
cin >> (tree_2 + i)->data;
cin >> temp1;
cin >> temp2;

if (temp1 == '-')
(tree_2 + i)->left = -1;
else
{
(tree_2 + i)->left = (temp1 - '0');
findtree_2top[temp1 - '0'] = 1;
//cout << temp1 << endl;
}

if (temp2 == '-')
(tree_2 + i)->right = -1;
else
{
(tree_2 + i)->right = (temp2 - '0');
findtree_2top[temp2 - '0'] = 1;
//cout << temp2 << endl;
}
}

int treetop1 = findtop(findtree_1top, treenum_1);
int treetop2 = findtop(findtree_2top, treenum_2);

if (travel(treetop1, treetop2))
cout << "Yes";
else
cout << "No";
}

}
else
{
cout << "No";
}
delete[]findtree_1top;
delete[]findtree_2top;
delete[]tree_1;
delete[]tree_2;

}

int main()
{
input();
return 0;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：14705次
• 积分：411
• 等级：
• 排名：千里之外
• 原创：26篇
• 转载：0篇
• 译文：0篇
• 评论：2条
文章分类
评论排行
最新评论