# 7-3 树的同构（25 分）

### 输入样例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>
//#include<string>
#include<vector>
#define LEN 10

using namespace std;

typedef struct TreeNode{
int father;
char letter;
int left;
int right;
}treeNode;
vector<treeNode> treea(LEN, {-1, '#', -1, -1});
vector<treeNode> treeb(LEN, {-1, '#', -1, -1});

int input(vector<treeNode> &tree);
int findRoot(int n, vector<treeNode> tree);
bool bfs(int a, int b);

int main()
{
int na, nb;
na = input(treea);
nb = input(treeb);
//	for(int i = 0; i < na; ++i){
//		cout<<treea[i].letter<<" "<<treea[i].left<<" "<<treea[i].right<<endl;
//	}
if(na != nb) cout<<"No"<<endl;
else{
if(na == 0 && nb == 0) cout<<"Yes"<<endl;
else{
int a, b;
a = findRoot(na, treea);
b = findRoot(nb, treeb);
//			cout<<a<<b<<endl;
if(bfs(a,b)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}

int input(vector<treeNode> &tree)
{
int n;
cin>>n;
for(int i=0; i<n; ++i){
cin>>tree[i].letter;
char ch;
cin>>ch;
if(ch != '-'){
tree[i].left = ch - '0';
tree[tree[i].left].father = i;
}
cin>>ch;
if(ch != '-'){
tree[i].right = ch - '0';
tree[tree[i].right].father = i;
}
}
return n;
}

int findRoot(int n, vector<treeNode> tree)
{
for(int i = 0; i<n; ++i) if(tree[i].father == -1) return i;
}

bool bfs(int a, int b)
{
if(treea[a].letter != treeb[b].letter) return false;

if(a == -1 && b == -1) return true;
else{
if(a == -1 || b == -1) return false;

if(bfs(treea[a].left, treeb[b].right) && bfs(treea[a].right, treeb[b].left)) return true;

if(bfs(treea[a].left, treeb[b].left) && bfs(treea[a].right, treeb[b].right)) return true;

return false;
}
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120