PTA 数据结构 03-树1 树的同构 (25分)

PTA 数据结构 03-树1 树的同构(25分)PTA 数据结构 03-树1 树的同构(25分)PTA 数据结构 03-树1 树的同构(25分)下面给出老师的代码:

`#include
#define Null -1
#define MaxTree 10
#define Tree int
#define ElementType char
using namespace std;

struct TreeNode
{
Tree Left;
Tree right;
ElementType Element;
}T1[MaxTree],T2[MaxTree];

Tree BuildTree(TreeNode T[])
{
int n,i,*check,Root=-1;
char cL,cR;
cin>>n;
check=new int[n];
if(n)
{
for(i=0;i<n;i++)check[i]=0;
for(i=0;i<n;i++)
{
cin>>T[i].Element>>cL>>cR;
if(cL!=’-’)//对cL的处理
{
T[i].Left=cL-‘0’;
check[T[i].Left]=1;
}
else
T[i].Left=Null;
if(cR!=’-’)//对cR的处理
{
T[i].right=cR-‘0’;
}
else
T[i].right=Null;
}
for(i=0;i<n;i++)
if(!check[i])Root=i;
}
return Root;
}
int Isomorphic(Tree R1,Tree R2)
{
if(R1Null&&R2Null)//both empty
return 1;
if((R1Null&&R2!=Null) || (R1!=Null&&R2Null))//one of them is empty
return 0;
if(T1[R1].Element!=T2[R2].Element)//Root is not different
return 0;
if((T1[R1].LeftNull)&&(T2[R2].LeftNull))
return Isomorphic(T1[R1].right,T1[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);
R2=BuildTree(T2);
if(Isomorphic(R1,R2))
cout<<“Yes”;
else
cout<<“No”;
return 0;
}`

相关文章: