#include<iostream>
using namespace std;
#define MaxTree 10
struct TreeNode
{
char Element;
int left;
int right;
};
struct TreeNode T1[MaxTree];
struct TreeNode T2[MaxTree];
int BulidTree(struct TreeNode T[])
{
int N;
int check[MaxTree];
int Root=-1;
cin>>N;
if(N){
for(int i=0;i<N;i++){
check[i]=0;
}
for(int i=0;i<N;i++){
cin>>T[i].Element;
char a,b;
cin>>a>>b;
if(a!='-'){
T[i].left=a-'0';
check[T[i].left]=1;
}
else T[i].left=-1;
if(b!='-'){
T[i].right=b-'0';
check[T[i].right]=1;
}
else T[i].right=-1;
}
for(int i=0;i<N;i++)
if(check[i]==0) Root=i;
}
return Root;
}
int lsomorphic(int r1,int r2)
{
if(r1==-1 && r2==-1) return 1;
if((r1!=-1 && r2==-1) || (r1==-1 && r2!=-1)) return 0;
if(T1[r1].Element !=T2[r2].Element) return 0;
if(T1[r1].left==-1 && T2[r2].left==-1) return(lsomorphic(T1[r1].right,T2[r2].right));
if ( ((T1[r1].left!=-1) && (T2[r2].left!=-1)) && ((T1[T1[r1].left].Element)==(T2[T2[r2].left].Element)))
return ( lsomorphic( T1[r1].left, T2[r2].left ) && lsomorphic( T1[r1].right, T2[r2].right ) );
else
return ( lsomorphic( T1[r1].left, T2[r2].right) && lsomorphic( T1[r1].right, T2[r2].left ) );
}
int main()
{
int r1,r2;
r1=BulidTree(T1);
r2=BulidTree(T2);
if(lsomorphic(r1,r2))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
return 0;
}
附:根据二叉树后序遍历和中序遍历输出先序遍历(递归调用)
void solve(int preL,int inL,int postL,int n){
int L,R;
int root;
if(n==0) return;
if(n==1){
pre[preL]=post[postL];
return;
}
root=post[n+postL-1];
pre[preL]=root;
for(int i=0;i<n;i++){
L=i; R=n-L-1;
if(in[i+inL]==root) break;
}
solve(preL+1,inL,postL,L);
solve(preL+1+L,inL+L+1,postL+L,R);
}