PTA Data Structures and Algorithms (English) 6-7
阿新 • • 發佈:2021-01-25
6-7Isomorphic(20point(s))
Two trees,
T1
andT2
, areisomorphicifT1
can be transformed intoT2
by swapping left and right children of (some of the) nodes inT1
. For instance, the two trees in Figure 1 are isomorphic because they are the same if the children of A, B, and G, but not the other nodes, are swapped. Give a polynomial time algorithm to decide if two trees are isomorphic.
Format of functions:
int Isomorphic( Tree T1, Tree T2 );
whereTree
is defined as the following:
typedef struct TreeNode *Tree;
struct TreeNode {
ElementType Element;
Tree Left;
Tree Right;
};
The function is supposed to return 1 ifT1
andT2
are indeed isomorphic, or 0 if not.
Sample program of judge:
#include <stdio.h> #include <stdlib.h> typedef char ElementType; typedef struct TreeNode *Tree; struct TreeNode { ElementType Element; Tree Left; Tree Right; }; Tree BuildTree(); /* details omitted */ int Isomorphic( Tree T1, Tree T2 ); int main() { Tree T1, T2; T1 = BuildTree(); T2 = BuildTree(); printf(“%d\n”, Isomorphic(T1, T2)); return 0; } /* Your function will be put here */
Example:
int Isomorphic( Tree T1, Tree T2 )
{
if(T1 && T2) {
if(T1->Element == T2->Element) {
if(Isomorphic(T1->Left, T2->Left)
&& Isomorphic(T1->Right, T2->Right)) {
return 1;
} else if(Isomorphic(T1->Left, T2->Right)
&& Isomorphic(T1->Right, T2->Left)) {
return 1;
}
}
} else if(!T1 && !T2) {
return 1;
}
return 0;
}