判别两二叉树是否同构
#include<stdio.h>
using namespace std;
#define MAXSIZE 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode
{
ElementType Element;
Tree Left,Right;
}T1[MAXSIZE],T2[MAXSIZE];
Tree BuildTree(struct TreeNode T[])
{
Tree Root;
int n;
scanf("%d\n",&n);
if(n)
{
int check[MAXSIZE];
for(int i=0;i<n;i++)
check[i]=0;
for(int i=0;i<n;i++)
{
char cl,cr;
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;
}
int i;
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;
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);
R2=BuildTree(T2);
if(Isomorphic(R1,R2))
printf("Yes\n");
else
printf("No\n");
}
问题分为三个部分:二叉树的表示,二叉树的建立,判别是否同构。
二叉树的表示比较简单,表示出代表的字母,左右子树对应的位置即可。
二叉树的建立因为需要返回根结点,所以用到了check[]数组,当出现左右子树对应的位置时,将对应的check[]位置置为1,最后剩下为0的位置即为树根。读入时cl,cr都设为char类型,用来判断是否为’-’,若不是则通过cl(cr)-‘0’,恢复到int类型,并存储到对应的T[i].Left or T[i].Right中去。
同构判别则需要考虑多种情况,两树是否都为空,是否其中一个数为空,是否根不相同,是否左子树为空,是否左根相同即位置对应,是否位置相反。
代码写完运行调试时发现按照对应的例子输入后还需要额外多输入一次,检查了n遍后也不知道问题出在哪里,日后再看也许会有新的发现吧。