数据结构实验之二叉树一:树的同构
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
Input
输入数据包含多组,每组数据给出2棵二叉树的信息。对于每棵树,首先在一行中给出一个非负整数N (≤10),即该树的结点数(此时假设结点从0到N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出”-”。给出的数据间用一个空格分隔。
注意:题目保证每个结点中存储的字母是不同的。
Output
如果两棵树是同构的,输出“Yes”,否则输出“No”。
Example Input
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 -
Example Output
Yes
Hint
测试数据对应图1
Author
xam
think:
这道题的思路是:
运用结构体,先将各个节点以及左右的链接点存起来,然后寻找根节点,比较两个结构体的各个元素以及左右节点。
#include<bits/stdc++.h>
using namespace std;
struct node
{
char t;//元素
int left, right;//左右节点
};
struct node t1[12], t2[12];//两个结构体
int BuildTree ( struct node t[], int N)
{
int i, check[12];//检查数组,寻找根节点
char cl, cr;
int Root;//返回
if(N!=0)
{
for(i=0;i<N;i++)
check[i] = 0;//清零
for(i=0;i<N;i++)
{
scanf(" %c %c %c", &t[i].t, &cl, &cr);
if(cl!='-')//如果不为空,将字符转换为整型
{
t[i].left = cl - '0';
check[t[i].left] = 1;//记录已有的节点
}
else t[i].left = -1;//空
if(cr!='-')//同理
{
t[i].right = cr - '0';
check[t[i].right] = 1;
}
else t[i].right =-1;
}
}
else
return -1;
for(i=0;i<N;i++)
{
if(check[i]==0)
break;
}
Root = i;//根节点
return Root;
}
int Isomorphic(int root1, int root2)//比较
{
if((root1==-1)&&(root2==-1))//都为空,YES
return 1;
if((root1==-1&&root2!=-1)||(root2==-1&&root1!=-1))
return 0;
if(t1[root1].t!=t2[root2].t)//元素不同
return 0;
if( (t1[root1].left == -1) && (t2[root2].left== -1) )
return Isomorphic(t1[root1].right,t2[root2].right ) ;
if( ((t1[root1].left!= -1) && (t2[root2].left!= -1))&& (( t1[ t1[root1].left ].t==t2[t2[root2].left].t )) )
return ( Isomorphic(t1[root1].left,t2[root2].left) &&
Isomorphic( t1[root1].right,t2[root2].right ) ) ;
return( Isomorphic( t1[root1].left,t2[root2].right ) &&
Isomorphic( t1[root1].right,t2[root2].left ) ) ;
}
int main()
{
int root1, root2;
int n;
while(~scanf("%d", &n))
{
getchar();//注意
root1 = BuildTree(t1, n);
scanf("%d", &n);
getchar();//注意
root2 = BuildTree(t2, n);
if(Isomorphic(root1, root2))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}
小结:
看了好多博客,才明白过来……
之前,我一直是按照自己的习惯来写代码,感觉typedef很麻烦的样子。
现在,我要尝试着写规范一点的代码,不然,别人的代码,我自己读不懂;自己的代码,其他人更加读不明白。