数据结构实验之二叉树一:树的同构
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
输入
输入数据包含多组,每组数据给出
2棵二叉树的信息。对于每棵树,首先在一行中给出一个非负整数
N (≤
10),即该树的结点数(此时假设结点从
0到
N−1编号);随后
N行,第
i行对应编号第
i个结点,给出该结点中存储的
1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出
”-”。给出的数据间用一个空格分隔。
注意:题目保证每个结点中存储的字母是不同的。
注意:题目保证每个结点中存储的字母是不同的。
输出
如果两棵树是同构的,输出“
Yes
”,否则输出“
No
”。
示例输入
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 -
示例输出
Yes
#include<bits/stdc++.h> struct node1 { char c; int l, r; } st[200]; struct node { char c; struct node *l, *r; }; bool vis[200]; int n1, n2, flag; int f(struct node *t1, struct node *t2) { if(!t1&&!t2)return 1; else if(t1&&t2) { if(t1->c==t2->c) flag++; else return 0; if((f(t1->l, t2->l)&&f(t1->r, t2->r))||(f(t1->l, t2->r)&&f(t1->r, t2->l)))return 1; else return 0; } else return 0; } struct node *creat(struct node *root, int x) { root=(struct node*)malloc(sizeof(struct node)); root->l=NULL; root->r=NULL; root->c=st[x].c; if(st[x].l!=-1) root->l = creat(root->l, st[x].l); else root->l = NULL; if(st[x].r!=-1) root->r = creat(root->r, st[x].r); else root->r = NULL; return root; }; int main() { struct node *t1, *t2; char a1[10],a2[10],a3[10]; while(~scanf("%d", &n1)) { memset(vis , 0, sizeof(vis)); for(int i = 0; i<n1; ++i) { scanf("%s%s%s",a1,a2,a3); st[i].c = a1[0]; if(a2[0]=='-')st[i].l = -1; else { st[i].l = a2[0]-'0'; vis[st[i].l] =1; } if(a3[0]=='-')st[i].r = -1; else { st[i].r = a3[0]-'0'; vis[st[i].r] = 1; } } for(int i = 0; i<n1; ++i) if(!vis[i]) { t1 = creat(t1, i); break; } scanf("%d", &n2); memset(vis , 0, sizeof(vis)); for(int i = 0; i<n2; ++i) { scanf("%s%s%s",a1,a2,a3); st[i].c = a1[0]; if(a2[0]=='-')st[i].l = -1; else { st[i].l = a2[0]-'0'; vis[st[i].l] =1; } if(a3[0]=='-')st[i].r = -1; else { st[i].r = a3[0]-'0'; vis[st[i].r] = 1; } } for(int i=0; i<=n2; ++i) if(!vis[i]) { t2=creat(t2,i); break; } flag = 0; f(t1, t2); if(flag==n1)printf("Yes\n"); else printf("No\n"); } return 0; }