程序框架搭建
int main()
{
// 建二叉树1
// 建二叉树2
// 判别是否同构并输出
return 0;
}
需要设计的函数:
- 读数据建二叉树
- 二叉树同构判别
int main()
{
Tree R1,R2;
// 建二叉树1
R1=BuildTree(T1);
// 建二叉树2
R2=BuildTree(T2);
// 判别是否同构并输出
if (Isomorphic(R1,R2)) printf("Yes\n");
else printf("No\n");
return 0;
}
如何建二叉树
Tree BuildTree(strcut TreeNode T[])
{
int N,check[MaxTree],i,Root=Null;
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.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) || (R2==Null && R1!=Null))
return 0;
if (T1[R1].Element != T2[R2].Element)
return 0;
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 return (Isomorphic(T1[R1].Left,T2[R2].Right) && Isomorphic(T1[R1].Right,T2[R2].Left));
}