1. 程式人生 > 其它 >PTA Data Structures and Algorithms (English) 6-7

PTA Data Structures and Algorithms (English) 6-7

技術標籤:PTA演算法c++

6-7Isomorphic(20point(s))

Two trees,T1andT2, areisomorphicifT1can be transformed intoT2by 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.

37

Format of functions:

int Isomorphic( Tree T1, Tree T2 );

whereTreeis defined as the following:

typedef struct TreeNode *Tree;
struct TreeNode {
    ElementType Element;
    Tree  Left;
    Tree  Right;
};

The function is supposed to return 1 ifT1andT2are 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;
}