include <stdio.h>
//Using struct arrays impresses double tree branches;
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1 // in the arrays,we can see it isn't pointer.so,using -1 impresses Null;
struct TreeNode{
ElementType Element;
Tree Left;
Tree Right;
}T1[MaxTree],T2[MaxTree];
int N,check[MaxTree];//check[] is used for searching Root;
Tree BuildTree(struct TreeNode T[]){
int Root = Null,i; //define Root =Null.if the tree is empty,then return -1;
char cl,cr;
scanf("%d\n",&N);
if(N){
for (i=0;i<N;i++)check[i]=0;
for(i=0;i<N;i++){
scanf("%c %c %c\n",&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(i=0;i<N;i++)
if(!check[i]) break;
Root=i;
}
return Root;
}
int Isomorphic(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;
//如果左儿子都为空判断右儿子是否同构:主要看以上三个方面(1)右儿子是否都为空(2)是否一个有右儿子一个没有(3)右儿子数据是否相同
if((T1[R1].Left==Null)&&(T2[R2].Left==Null))
return Isomorphic(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 ( Isomorphic( T1[R1].Left, T2[R2].Left )&&Isomorphic( T1[R1].Right, T2[R2].Right ) );
/* 如果两棵树左儿子(一个空一个不空或者都不空)并且数据不一样,那么判断第一棵树的左(右)儿子是否跟第二棵树的右(左)儿子同构 */
else
return ( Isomorphic( T1[R1].Left, T2[R2].Right)&&Isomorphic( T1[R1].Right, T2[R2].Left ) );
}
int main(){
Tree R1,R2;
R1 = BuildTree(T1); //set up tree 1;
R2 = BuildTree(T2);//set up tree 2;
if(Isomorphic(R1,R2)) printf("Yes\n");//judge whether the trees R the same;
else printf("No\n");
return 0;
}