这道题用的是静态链表的结构;
关键在于数同构的判别:
条件判别是从上到下从左到右
先看两个节点是否为空,值是否相等,再看左子树是否都为空判断右子树,继续看左子树是否都不为空且值也相等则判断左右子树,最后看左子树有一个为空或都不为空但值不同
那么交换左右子树判别;
还有一点:因为是静态链表, 这里找树根用了一个数组给每个节点加一个flag;
定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
输入格式:
输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数NNN (≤10\le 10≤10),即该树的结点数(此时假设结点从0到N−1N-1N−1编号);随后NNN行,第iii行对应编号第iii个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。
输出格式:
如果两棵树是同构的,输出“Yes”,否则输出“No”。
#include
#define OK 1
#define ERROR 0
#define MaxTree 10
#define Null -1
//区别于系统的NULL 0
#define ElementType char
typedef int Status;
typedef struct TreeNode
{
ElementType data;
int left;
int right;
} Tree;
Tree T1[MaxTree], T2[MaxTree];
int BulidTree(Tree T[])
{
int N, check[MaxTree], root = Null;
//root = Null 空树则返回Null
char cl, cr;
//左右孩子序号
int i;
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[i].data,&cl,&cr);
//找root
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++)
//check[]=0的为根节点
if(!check[i]) {
root = i;
break;
}
}
return root;
}
Status Isomprphic(int root1, int root2)
{
if( (root1 == Null) && (root2 == Null))
//都是空 ,同构
return OK;
if( (root1 == Null)&&(root2 != Null) || (root1 != Null)&&(root2 == Null))//其中一个为空,不同构
return ERROR;
if(T1[root1].data != T2[root2].data)
//根数据不同,不同构
return ERROR;
if( (T1[root1].left == Null) && (T2[root2].left == Null) )
//左子树为空,则判断右子树
return Isomprphic(T1[root1].right, T2[root2].right);
if((T1[root1].left != Null) && (T2[root2].left != Null) &&
( T1[T1[root1].left].data == T2[T2[root2].left].data) )
//两树左子树皆不空,且值相等
return (Isomprphic(T1[root1].left, T2[root2].left) &&
//判断其子树
Isomprphic(T1[root1].right, T2[root2].right) );
else //两树左子树有一个空 或者 皆不空但值不等
return (Isomprphic(T1[root1].left, T2[root2].right) &&
//交换左右子树判断
Isomprphic(T1[root1].right, T2[root2].left) );
}
int main()
{
int root1, root2;
root1 = BulidTree(T1);
root2 = BulidTree(T2);
if(Isomprphic(root1, root2) )
printf("Yes\n");
else
printf("No\n");
return 0;
}