如何判断两颗二叉树同构

如何判断两颗二叉树同构_第1张图片

如何判断两颗二叉树同构_第2张图片

如何判断两颗二叉树同构_第3张图片

如何判断两颗二叉树同构_第4张图片如何判断两颗二叉树同构_第5张图片如何判断两颗二叉树同构_第6张图片如何判断两颗二叉树同构_第7张图片

#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode{
ElementType Element; 
Tree Left;
Tree Right; 
}T1[MaxTree],T2[MaxTree],T[MaxTree];
int main()
{
Tree R1,R2;
R1=BuildTree(T1);
R2=BuildTree(T2);
if(Isomorphic(R1,R2)) printf("Yes\n");
else printf("No\n"); 
return 0;

Tree BuildTree(struct TreeNode T[])//如何建二叉树 

if(N){
for(i=0;ifor(i=0;iscanf("%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;
//对cr的对应处理 
}
for(i=0;iif(!check[i]) break;
Root=i;
}
return Root;
}
int Isomorphic(Tree R1,Tree R2)//如何判别两二叉树同构 
{
if((R1==Null)&&(R2==Null))//both empty
return 1;
if((R1==Null)&&(R2==Null)||((R1!=Null)&&(R2!=Null)))
return 0;//one of them is empty
if(T1[R1].Element!=T2[R2].Element)
return 0;//roots are different
if((T1[R1].Left==Null)&&(T2[R2].Left==Null))
//both have no left subtree
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)))
  //no need to swap the left and the right
  return(Isomorphic(T1[R1].Left,T2[R2].Left)&&
    Isomorphic(T1[R1].Right,T2[R2].Right));
else//need to swap the left and the right
return(Isomorphic(T1[R1].Left,T2[R2].Right)&& 
  Isomorphic(T1[R1].Right,T2[R2].Left));

你可能感兴趣的:(数据结构和算法)