给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
输入格式:
输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数NNN (≤10le 10≤10),即该树的结点数(此时假设结点从0到N−1N-1N−1编号);随后NNN行,第iii行对应编号第iii个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。
输出格式:
如果两棵树是同构的,输出“Yes”,否则输出“No”。
输入样例1(对应图1):
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 -
输出样例1:
Yes
输入样例2(对应图2):
8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4
输出样例2:
No
==========================
第一次code:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 5 /* 6 结构数组表示二叉树:静态链表 7 */ 8 #define MaxTree 100 9 #define ElementType char 10 #define Tree int 11 #define Null -1 12 13 struct TreeNode 14 { 15 ElementType Element; 16 Tree Left; 17 Tree Right; 18 } T1[MaxTree],T2[MaxTree]; 19 20 Tree BuildTree(struct TreeNode T[]); 21 int isSame(Tree R1,Tree R2); 22 int main(void) 23 { 24 Tree R1,R2; 25 R1 = BuildTree(T1); 26 R2 = BuildTree(T2); 27 if(isSame(R1,R2)) 28 { 29 printf("Yes "); 30 } 31 else 32 { 33 printf("No "); 34 } 35 return 0; 36 } 37 /* 38 建立二叉树 39 */ 40 Tree BuildTree(struct TreeNode T[]) 41 { 42 int N,i,Root; 43 ElementType cl,cr; 44 int check[MaxTree] = {1}; 45 scanf("%d ",&N); 46 if( N ) 47 { 48 for(i = 0;i < N;i++) 49 { 50 check[i]=0; 51 } 52 for(i = 0;i < N;i++) 53 { 54 scanf("%c %c %c ",&T[i].Element,&cl,&cr); 55 if(cl != '-') 56 { 57 T[i].Left = cl-'0'; 58 check[T[i].Left] = 1; 59 } 60 else 61 { 62 T[i].Left = Null; 63 } 64 if(cr != '-') 65 { 66 T[i].Right = cr-'0'; 67 check[T[i].Right] = 1; 68 } 69 else 70 { 71 T[i].Right = Null; 72 } 73 } 74 for(i = 0;i < N;i++) 75 { 76 if(!check[i]) 77 { 78 Root = i; 79 break; 80 } 81 } 82 } 83 return Root; 84 } 85 /* 86 判断是否同构 87 */ 88 int isSame(Tree R1,Tree R2) 89 { 90 if((R1 == Null) && (R2 == Null)) 91 { 92 return 1; 93 } 94 if( (R1 == Null && R2 != Null) || (R1 != Null && R2 == Null)) 95 { 96 return 0; 97 } 98 else 99 { 100 if(T1[R1].Element != T2[R2].Element) 101 { 102 return 0; 103 } 104 if(T1[R1].Left == Null && T2[R2].Left == Null) 105 { 106 return isSame(T1[R1].Right,T2[R2].Right); 107 } 108 if((T1[R1].Left != Null && T2[R2].Left != Null) && (T1[R1].Element != T2[R2].Element)) 109 { 110 return (isSame(T1[R1].Left,T2[R2].Left) && isSame(T1[R1].Right,T2[R2].Right)); 111 } 112 else 113 { 114 return (isSame(T1[R1].Left,T2[R2].Right) && isSame(T1[R1].Right,T2[R2].Left)); 115 } 116 } 117 }