1. 程式人生 > >PTA——樹的同構

PTA——樹的同構

pre 一個 break uil clu turn 相等 scan element

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",&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\n",&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\n"); 68 else printf("No\n"); 69 return 0; 70 }

分析:

1、用數組存儲樹,結點無序

2、需找出樹的根結點

3、判斷是否同構要考慮周全

PTA——樹的同構