1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include<iostream> #include<vector> using namespace std; #define Null -1 typedef char ElemType; struct TreeNode { ElemType Data; int lchild; int rchild; }; int TreeCreate(vector<TreeNode> &t, int n); bool isomorphic(vector<TreeNode> &t1, int t1Root, vector<TreeNode> &t2, int t2Root); int t1Root; int t2Root; int main() { int n; cin >> n; vector<TreeNode> t1(n); t1Root = TreeCreate(t1, n); cin >> n; vector<TreeNode> t2(n); t2Root = TreeCreate(t2, n); if (isomorphic(t1, t1Root, t2, t2Root)) cout << "Yes" << endl; else cout << "No" << endl; return 0; } int TreeCreate(vector<TreeNode> &t, int n) { int root = -1; vector<int> arr(n, 1); for (int i = 0; i < n; i++) { char cl, cr; cin >> t[i].Data >> cl >> cr; if (cl == '-') t[i].lchild = Null; else { t[i].lchild = cl - '0'; arr[t[i].lchild] = 0; } if (cr == '-') t[i].rchild = Null; else { t[i].rchild = cr - '0'; arr[t[i].rchild] = 0; } } for (int i = 0; i < n; i++) { if (arr[i] != 0) { root = i; break; } } return root; }
bool isomorphic(vector<TreeNode> &t1, int t1Root, vector<TreeNode> &t2, int t2Root) { if (t1Root == Null && t2Root == Null) return true; else if ((t1Root != Null && t2Root == Null) || (t1Root == Null && t2Root != Null)) return false; else if (t1[t1Root].Data != t2[t2Root].Data) return false; else if (t1[t1Root].lchild == Null && t2[t2Root].lchild == Null) return isomorphic(t1, t1[t1Root].rchild, t2, t2[t2Root].rchild); else if ((t1[t1Root].lchild != Null && t2[t2Root].lchild != Null) && (t1[t1[t1Root].lchild].Data == t2[t2[t2Root].lchild].Data)) return isomorphic(t1, t1[t1Root].lchild, t2, t2[t2Root].lchild) && isomorphic(t1, t1[t1Root].rchild, t2, t2[t2Root].rchild); else return isomorphic(t1, t1[t1Root].rchild, t2, t2[t2Root].lchild)&& isomorphic(t1, t1[t1Root].lchild, t2, t2[t2Root].rchild);
}
|