#include<stdio.h>
#define MaxTree 100
#define ElementType char
#define Tree int
//定义一个树的结构体,这里采用一个静态链表存储
struct TreeNode{
ElementType data;
Tree LeftTree;
Tree RightTree;
}T1[MaxTree],T2[MaxTree];
//建立树的函数
int buildTree(struct TreeNode T[]){
//输入结点的个数
int N;
scanf("%d",&N);
if(N<=0){
return -1;
}
//定义一个测试数组来判断结点是否有双亲,初始值赋值为0
int test[N];
for(int i=0;i<N;i++){
test[i]=0;
}
for(int i=0;i<N;i++){
char ch1;
char ch2;
scanf("%c %c %c",&T[i].data,&ch1,&ch2);
if(ch1!='-')
{ //如果左孩子不为空就成为对应结点的左孩子
T[i].LeftTree=ch1-'0';
test[ T[i].LeftTree]=1; //左孩子标号的那个结点就是有双亲的了
}
else
T[i].LeftTree=-1; //左孩子为空则标记为-1
if(ch2!='-')
{
T[i].RightTree=ch2-'0';
test[ T[i].RightTree]=1;
}
else
T[i].RightTree=-1;
}
for(int j=0;j<N;j++)
{ //从0开始逐一判断每个结点是否有双亲
if(!test[j]) //没有双亲的就是根结点
return j;
}
}
//判断树是否同构并输出
int isSame(int root1,int root2){
//只要有树空则不同构
if(root1==-1||root2==-1){
return 0;
}
//非空但结点数据不相等则不同构
if(T1[root1].data!=T2[root2].data)
return 0;
//继续递归比较左子树和左子树 ,右子树和右子树
if(isSame(T1[root1].LeftTree,T2[root2].LeftTree)&&isSame(T1[root1].RightTree,T2[root2].RightTree)){
return 1;
}
//递归比较a的左与b的右子树
if(isSame(T1[root1].RightTree,T2[root2].LeftTree)&&isSame(T1[root1].LeftTree,T2[root2].RightTree)){
return 1;
}
return 0;//都不同构返回0;
}
//主函数
int main(){
Tree r1,r2;
r1=buildTree(T1);
r2=buildTree(T2);
if(isSame(r1,r2)){
printf("Yes");
}else{
printf("No");
}
return 0;
}
递归法进行二叉树同构判定
最新推荐文章于 2023-06-10 13:01:31 发布