题目
给定两棵树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;
struct Node{
char ch;
int left,right;
}a[15],b[15];//creat tree
int flag;
void m_swap(int x){//交换左右子树
int tmp;
tmp = b[x].left;
b[x].left=b[x].right;
b[x].right = tmp;
}
bool even(int root1,int root2){//判断子树的左右孩子个数,不匹配则不同构
int cnt_1 = 2,cnt_2 = 2;
if(a[root1].left == -1) --cnt_1;
if(a[root1].right== -1) --cnt_1;
if(b[root2].left == -1) --cnt_2;
if(b[root2].right== -1) --cnt_2;
if(cnt_1==cnt_2)
return true;
else
return false;
}
void judge(int root1,int root2){
if((root1 == -1 && root2 == -1)||(flag == 1)) return ;//判空
if((a[root1].ch != b[root2].ch)||(!even(root1,root2))){
flag = 1;
return ;
}
//子树数目相同,左孩子不匹配则交换
if((a[root1].left==-1)&&(b[root2].left!=-1))
m_swap(root2);
else if(a[root1].left!=-1&&b[root2].left==-1)
m_swap(root2);
else if(a[root1].left!=-1){
if((a[a[root1].left].ch != b[b[root2].left].ch)&&(a[root1].right!=-1))
m_swap(root2);
}
//左右子树为空不予继续判定
if(a[root1].left!=-1&&b[root2].left!=-1) judge(a[root1].left,b[root2].left);
if(a[root1].right!=-1&&b[root2].right!=-1) judge(a[root1].right,b[root2].right);
}
int input(struct Node tree[]){//creat tree and find root
int n,root=-1;
int k[10]={0};
char ch,l,r;
cin >> n;
for(int i = 0;i<n;++i){
scanf(" %c %c %c",&ch,&l,&r);
tree[i].ch = ch;
if(l=='-') tree[i].left=-1;
else {
tree[i].left = l-'0';
k[tree[i].left]=1;
}
if(r=='-') tree[i].right=-1;
else {
tree[i].right= r-'0';
k[tree[i].right]=1;
}
}
for(int i = 0;i<n;++i)
if(k[i]!=1) root = i;
return root;
}
int main()
{
int root1=0,root2=0;
root1=input(a);
root2=input(b);
judge(root1,root2);
if(flag) cout <<"No"<<endl;
else cout <<"Yes";
return 0;
}