判别二叉树是否同构。
利用静态链表储存两棵二叉树,文件第一行是结点的个数。
T1.txt和T2.txt文件中的内容如下('-'代表没有左孩子/右孩子,在结构数组中以-1代替):
7
E - 2
D - -
B 1 4
A 5 6
F - -
G - 7
C - -
7
A 6 7
B 1 3
E - 4
D - -
C - -
G - 5
F - -
#define MaxTree 10
#define ElemType char
#define Tree int
#define Null -1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//判别两颗二叉树是否同构
struct TreeType{
ElemType elem;
Tree Left;
Tree Right;
}T1[MaxTree],T2[MaxTree];
//从文件读取一棵树并初始化,并返回根结点下标
int BuiltTree(struct TreeType T[],FILE *fp){
int length,i,root;
char L[2],R[2];
int check[MaxTree] = {0};
length = fgetc(fp)-'0';
printf("\nlength=%d",length);
for (i=0;i<length;i++){
// fgetc(fp);
// fscanf(fp,"%c%s%s",&T[i].elem,L,R); //这行和下一行有较大区别!
fscanf(fp," %c%s%s",&T[i].elem,L,R); //%s遇到空格结束读取
if (!strcmp(L,"-")) T[i].Left = Null;
else {
T[i].Left = atoi(L) - 1;
check[T[i].Left] = 1;
}
if (!strcmp(R,"-")) T[i].Right = Null;
else {
T[i].Right = atoi(R) - 1;
check[T[i].Right] = 1;
}
printf("\n%3c %3d %3d",T[i].elem,T[i].Left,T[i].Right);
}
printf("\n打印完成!\n");
for (i=0;i<length;i++){
if (check[i] != 1){
root = i;
break;
}
}
return root;
}
//判别两颗二叉树是否同构
int Isomorphic(Tree r1,Tree r2){
//比较根结点
printf("\n当前根 %d %d",r1,r2);
printf("\n============compare %c %c",T1[r1].elem,T2[r2].elem);
if (r1==Null && r2==Null)
return 1;
if (((r1==Null) && (r2!=Null)) || ((r1!=Null && r2==Null)))
return 0;
if (T1[r1].elem != T2[r2].elem)
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].elem) == (T2[T2[r2].Left].elem))){
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()
{
FILE *fp1,*fp2;
Tree R1,R2;
int i;
if ((fp1 = fopen("T1.txt","r")) == NULL){
printf("\ncannot open file T1");
exit(0);
}
if ((fp2 = fopen("T2.txt","r")) == NULL){
printf("\ncannot open file T2");
exit(0);
}
R1 = BuiltTree(T1,fp1);
R2 = BuiltTree(T2,fp2);
if (Isomorphic(R1,R2)){
printf("\n结果:这两棵树同构");
}else{
printf("\n结果:这两棵数不同构");
}
fclose(fp1);
fclose(fp2);
return 0;
}
结果输出:
当前根 2 1
============compare B B
当前根 0 2
============compare E E
当前根 1 3
============compare D D
当前根 -1 -1
============compare
当前根 3 0
============compare A A
当前根 4 6
============compare F F
当前根 -1 -1
============compare
当前根 5 5
============compare G G
当前根 6 4
============compare C C
当前根 -1 -1
============compare
结果:这两棵树同构
第一次发文章,大家多多交流呀!