1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdbool.h> 5 6 typedef char ElemType; 7 8 typedef struct BinTree 9 { 10 ElemType data; 11 struct BinTree *left; 12 struct BinTree *right; 13 }BinTree; 14 15 16 bool TreeCmp(BinTree * a, BinTree * b); //判断a树与b树是否同构 17 BinTree * BinTree_new(int n); 18 19 int main() 20 { 21 int n; 22 scanf("%d", &n); 23 BinTree * a = BinTree_new(n); 24 scanf("%d", &n); 25 BinTree * b = BinTree_new(n); 26 27 bool flag = TreeCmp(a, b); 28 if (flag) 29 printf("Yes"); 30 else 31 printf("No"); 32 33 return 0; 34 } 35 36 BinTree * BinTree_new(int n) 37 { 38 if (n == 0) 39 { 40 return NULL; 41 } 42 else 43 { 44 int i, li, ri; 45 ElemType c, lc, rc; 46 BinTree * T = (BinTree *)malloc(n * sizeof(BinTree)); 47 bool *head = (bool *)malloc(n * sizeof(bool)); 48 49 memset(head, true ,sizeof(head)); 50 51 for ( i = 0; i < n ; ++i ) 52 { 53 scanf(" %c %c %c", &c, &lc, &rc); 54 55 li = lc-‘0‘; 56 ri = rc-‘0‘; 57 58 T[i].data = c; 59 60 if (lc != ‘-‘) 61 { 62 T[i].left = &T[li]; 63 head[li] = false; 64 } 65 else 66 T[i].left = NULL; 67 68 if (rc != ‘-‘) 69 { 70 T[i].right = &T[ri]; 71 head[ri] = false; 72 } 73 else 74 T[i].right = NULL; 75 76 } 77 78 //寻找树的树根(树根没有其它的结点指向它) 79 for ( i = 0; i < n ; ++i ) 80 if (head[i] == true) 81 break; 82 free(head); 83 return &T[i]; 84 } 85 } 86 87 bool TreeCmp(BinTree * a, BinTree * b) 88 { 89 if (a == NULL && b == NULL)//两棵树都为空 90 return true; 91 92 if (a == NULL || b == NULL)//有一棵树为空 93 return false; 94 95 if (a->data != b->data)//树结点的值不相等 96 return false; 97 98 if (a->left == NULL && b->left == NULL)//两棵树的左子树都为空 99 return TreeCmp(a->right, b->right);//就比较右子树 100 101 //两棵树的左子树都不为空,且两个值相等就比较两棵树的子树 102 if (a->left != NULL && b->left != NULL &&(a->left->data == b->left->data)) 103 return (TreeCmp(a->left,b->left)&&TreeCmp(a->right,b->right)); 104 105 //交换后再比较 106 else 107 return (TreeCmp(a->left,b->right)&&TreeCmp(a->right,b->left)); 108 }
时间: 2024-10-06 11:43:07