数据结构实验之二叉树一:树的同构
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
以下为accepted代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
char date;
int left;
int right;
} BinTree;
BinTree t1[24], t2[24];
int n, m;
void build_tree(BinTree *t, int nm)
{
int i;
for(i = 0; i < nm; i++)
{
char s[10];
scanf("%s", s);
t[i].date = s[0];
scanf("%s", s);
if(s[0] == '-')
t[i].left = -1;
else
t[i].left = s[0] - '0';
scanf("%s", s);
if(s[0] == '-')
t[i].right = -1;
else
t[i].right = s[0] - '0';
}
}
int judge(int i, int j)
{
if(t1[t1[i].left].date == t2[t2[j].left].date && t1[t1[i].right].date == t2[t2[j].right].date)
return 1;
if(t1[t1[i].left].date == t2[t2[j].right].date && t1[t1[i].right].date == t2[t2[j].left].date)
return 1;
return 0;
}
void ans()
{
int i, j;
int flag = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(t1[i].date == t2[j].date)
{
if(judge(i, j) == 0)
{
flag = 1;
break;
}
else
break;
}
}
if(j == m)
{
flag = 1;
break;
}
}
if(flag)
printf("No\n");
else
printf("Yes\n");
}
int main()
{
while(scanf("%d", &n) != EOF)
{
build_tree(t1, n);
scanf("%d", &m);
build_tree(t2, m);
ans();
}
return 0;
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 120KB
Submit time: 2017-02-08 21:51:01
****************************************************/