binary tree One of data structure experiments: isomorphism of treesTime limit:1000ms Memory limit:65536kb Submit statistic
problem Description
Given two trees T1 and T2. If T1 can be converted to T2 by several times or so, we call the two trees "isomorphic". For example, the two trees given in Figure 1 are isomorphic because we swap the children of the nodes A, B, and g of one of the trees to get another tree. and Figure 2 is not isomorphic.
Figure 1
Figure 2
Now given two trees, please judge whether they are isomorphic. input data contains more than one group, each set of data gives 2 binary tree information. For each tree, first, a non-negative integer N (≤10) is given in a row, that is, the node number of the tree (at this point the node is assumed to be numbered from 0 to n−1), and then N lines, the line I corresponds to the number I node, give the node stored in the 1 English capital letters, their left child node number, right child node number 。 If the child's node is empty, the "-" is given in the appropriate location. The given data is separated by a single space.
Note: The title guarantees that the letters stored in each node are different. Output If the two trees are isomorphic, export "Yes", otherwise output "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
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace Std;
typedef struct BITNODE
{
char data;
struct Bitnode *lchild,*rchild;
}*bitree;
struct node
{
Char ch;
int l,r;
} A[20];
Bitree Intibitree (bitree &t,int i)
{
T=new Bitnode;
if (! T) exit (-1);
t->lchild=null;
t->rchild=null;
t->data=a[i].ch;
if (a[i].l!=-1)
Intibitree (T->LCHILD,A[I].L);
if (a[i].r!=-1)
Intibitree (T->RCHILD,A[I].R);
return T;
}
Bitree Create (int n)
{
int i,k;
int b[20]= {0};//b[i]==1 means someone else's child
Char str1[20],str2[20],str3[20];
for (i=0; i<n; i++)
{
scanf ("%s%s%s", STR1,STR2,STR3);
A[I].CH=STR1[0];
if (str2[0]!= '-')
{
a[i].l=str2[0]-' 0 ';
B[a[i].l]=1;
}
Else
A[i].l=-1;
if (str3[0]!= '-')
{
a[i].r=str3[0]-' 0 ';
B[a[i].r]=1;
}
else A[i].r=-1;
}
for (k=0; k<n; k++)
{
if (!b[k])
Break
}
Bitree T=intibitree (t,k);
return T;
}
int Bijiao (Bitree &t1,bitree &t2)
{
if (! t1&&! T2)
return 1;
if (T1&&T2)
{
if (T1->data==t2->data)
if ((Bijiao (T1->lchild,t2->lchild) &&bijiao (t1->rchild,t2->rchild)) | | (Bijiao (T1->lchild,t2->rchild) &&bijiao (t1->rchild,t2->lchild)))
return 1;
}
return 0;
}
/*void print (Bitree T)
{
if (T)
{
printf ("%c\n", t->data);
if (t->lchild)
Print (T->lchild);
if (t->rchild)
Print (T->rchild);
}
}*/
int main ()
{
int m,n;
Bitree t1,t2;
while (~SCANF ("%d", &n))
{
T1=create (n);
scanf ("%d", &m);
T2=create (m);
if (Bijiao (T1,T2))
printf ("yes\n");
Else
printf ("no\n");
Print (T1);
printf ("\ n");
Print (T2);
}
return 0;
}