给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。
输入格式:
输入给出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>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode{
ElementType Element;
Tree left;
Tree right;
}T1[MaxTree],T2[MaxTree];
Tree BuildTree(struct TreeNode T[]);
Tree Isomsorphic(Tree R1,Tree R2);
int main()
{
Tree R1,R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
if(Isomsorphic(R1,R2))
cout << "Yes" <<endl;
else cout << "No" <<endl;
return 0;
}
Tree BuildTree(struct TreeNode T[]){
int num;
char cL,cR,c;
Tree Root = Null;
cin >> num;
Tree check[MaxTree] = {0};
if(num){
for(int i = 0;i < num;i++){
cin >> T[i].Element >> cL >> cR;
if(cL != '-'){
T[i].left = cL- '0';
check[T[i].left] = 1;
}else{
T[i].left = Null;
}
if(cR != '-'){
T[i].right = cR- '0';
check[T[i].right] = 1;
}else{
T[i].right = Null;
}
}
for(int i = 0;i < num ; i++){
if(check[i] == 0){
Root = i;
break;
}
}
}
return Root;
}
Tree Isomsorphic(Tree R1,Tree R2){
if(R1 == Null && R2 == Null){
return 1;
}
if((R1 == Null && R2 != Null)||(R1 != Null && R2 == Null)){
return 0;
}
if(T1[R1].Element != T2[R2].Element){
return 0;
}
if(T1[R1].left == Null && T2[R2].left == Null){
return Isomsorphic(T1[R1].right,T2[R2].right);
}
if((T1[R1].left != Null && T2[R2].left != Null) && T1[T1[R1].left].Element == T2[T2[R2].left].Element){
return (Isomsorphic(T1[R1].left,T2[R2].left))&&(Isomsorphic(T1[R1].right,T2[R2].right));
}
else{
return (Isomsorphic(T1[R1].left,T2[R2].right)&&(Isomsorphic(T1[R1].right,T2[R2].left)));
}
}