[刷题] PTA 03-树1 树的同构

程序:

 1 #include <stdio.h>
 2 #define MaxTree 10
 3 #define ElementType char
 4 #define Tree int
 5 #define Null -1
 6 
 7 struct TreeNode {
 8     ElementType Element;
 9     Tree Left;
10     Tree Right;
11 } T1[MaxTree],T2[MaxTree];
12 int N,check[MaxTree];
13 
14 Tree BuildTree(struct TreeNode T[]) {
15     int Root=Null,i;  //将根结点置为空,若为空树时返回Null 
16     char cl,cr;
17     scanf("%d
",&N);
18     if(N) {
19         for(i=0; i<N; i++) check[i]=0;  //将check[]置0 
20         for(i=0; i<N; i++) {
21             scanf("%c %c %c
",&T[i].Element,&cl,&cr);
22             if(cl!='-') {
23                 T[i].Left=cl-'0';
24                 check[T[i].Left]=1;
25             } else T[i].Left=Null;
26             if(cr!='-') {
27                 T[i].Right=cr-'0';
28                 check[T[i].Right]=1;
29             } else T[i].Right=Null;
30         }
31         for(i=0; i<N; i++)
32             if(!check[i]) break;
33         Root=i;
34     }
35     return Root;
36 }
37 
38 int Isomorphic(Tree R1,Tree R2) {
39     //都为空树则同构
40     if((R1==Null)&&(R2==Null))   
41         return 1;
42     //只有一个根结点为空则不同构 
43     if(((R1==Null)&&(R2!=Null))||((R1!=Null)&&(R2==Null))) 
44         return 0;
45     //根结点数据不同则不同构 
46     if(T1[R1].Element!=T2[R2].Element)  
47         return 0;
48     //左儿子都为空,判断右儿子是否同构 
49     if((T1[R1].Left==Null)&&(T2[R2].Left==Null))
50         return Isomorphic(T1[R1].Right,T2[R2].Right);
51     //左儿子结点都不为空且数据相等,对左儿子的左右子树进行递归 
52     if(((T1[R1].Left!=Null)&&(T2[R2].Left!=Null))&&
53             ((T1[T1[R1].Left].Element)==(T2[T2[R2].Left].Element)))
54         return(Isomorphic(T1[R1].Left,T2[R2].Left)&&
55                Isomorphic(T1[R1].Right,T2[R2].Right));
56     //左儿子不一样,左右交换后递归 
57     else
58         return(Isomorphic(T1[R1].Left,T2[R2].Right)&&
59                Isomorphic(T1[R1].Right,T2[R2].Left));
60 }
61 
62 int main() {
63     Tree R1,R2;
64     R1=BuildTree(T1);
65     R2=BuildTree(T2);
66     if(Isomorphic(R1,R2))
67         printf("Yes
");
68     else printf("No
");
69     return 0;
70 }

分析:

1、用数组存储树,结点无序

2、需找出树的根结点

3、判断是否同构要考虑周全

原文地址:https://www.cnblogs.com/cxc1357/p/10808687.html