题意理解:
按格式输入两个二叉树,判断其是否同构
输入样例:
8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
//静态链表
struct TreeNode
{
ElementType Element;
Tree left;
Tree right;
}T1[MaxTree], T2[MaxTree];
Tree BuildTree(struct TreeNode T[]);
int Isomorphic(Tree R1, Tree R2);
int main()
{
Tree R1, R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
if(Isomorphic(R1,R2)) printf("yes\n");
else printf("no\n");
return 0;
}
Tree BuildTree(struct TreeNode T[]) //返回根节点
{
int N, i, Root=0;
printf("input the tree:\n");
scanf("%d",&N);
char cl, cr;
int check[N]; //check数组下标分别对应一个节点
for (i=0; i<N; i++){
check[i]=0;
}
if(N){ //若节点有左右儿子,则将其儿子所在位置置为1,表示有节点指向该位置,否则为0,则只有根节点唯一为0
for(i=0; i<N; i++){
printf("the node of %d:", i+1);
scanf(" %c",&T[i].Element);
scanf(" %c",&cl);
scanf(" %c",&cr);
if(cl != '-'){
T[i].left = cl-'0';
check[T[i].left] = 1;
}
if(cl == '-')
T[i].left = Null;
if(cr != '-'){
T[i].right = cr-'0';
check[T[i].right] = 1;
}
if(cr == '-')
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)) || ((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) && //否则将T1的左子树与T2的右子树比较,T1的右子树与T2的左子树比较
Isomorphic(T1[R1].right, T2[R2].left));
}