03-树1 树的同构 (25 分)
#include <cstdio> #define MaxTree 12 #define ElementType char #define Null -1 #define Tree int struct TreeNode { ElementType element; Tree left; Tree right; }t1[MaxTree], t2[MaxTree]; Tree buildTree(struct TreeNode* t); int isomorphic(Tree r1, Tree r2); int main() { Tree r1, r2; r1 = buildTree(t1); r2 = buildTree(t2); if(isomorphic(r1, r2)) printf("Yes\n"); else printf("No\n"); return 0; } Tree buildTree(struct TreeNode* t) { int n, cl, cr, hashT[MaxTree]; int root = -1; scanf("%d", &n); if(n) { for(int i=0; i<n; i++) hashT[i] = 0; for(int i=0; i<n; i++) { getchar(); scanf("%c %c %c", &t[i].element, &cl, &cr); if(cl != '-') { t[i].left = cl - '0'; hashT[t[i].left] = 1; } else t[i].left = Null; if(cr != '-') { t[i].right = cr - '0'; hashT[t[i].right] = 1; } else t[i].right = Null; } for(int i=0; i<n; i++) { if( !hashT[i] ) { root = i; break; } } } return root; } int isomorphic(Tree r1, Tree r2) { if((r1 == Null) && (r2 == Null)) return 1; else if((r1 != Null) && (r2 != Null)) { if(t1[r1].element != t2[r2].element) return 0; if(t1[r1].left == Null && t1[r2].left == Null) return (isomorphic(t1[r1].right, t2[r2].right)); else if((t1[r1].left != Null && t2[r2].left != Null) and t1[t1[r1].left].element == t2[t2[r2].left].element) return (isomorphic(t1[r1].left, t2[r2].left) && isomorphic(t1[r1].right, t2[r2].right)); else return (isomorphic(t1[r1].left, t2[r2].right) && isomorphic(t1[r1].right, t2[r2].left)) ; } else return 0; }