关于二叉树的同构
一种可行的方法(基于数组的二叉树)
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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| struct ArrTree { char data; int left; int right; }A1T[100], A2T[100]; bool check[100];
int AtBuild(ArrTree AT[]) { int root = 0;
int n; cin >> n;
char left, right; if (n) { for (int i = 0; i < n; i++)check[i] = false;
for (int i = 0; i < n; i++) { cin >> AT[i].data >> left >> right; if (left != '-') { AT[i].left = left - '0'; check[AT[i].left] = 1; } else { AT[i].left = -1; }
if (right != '-') { AT[i].right = right - '0'; check[AT[i].right] = 1; } else { AT[i].right = -1; } } for (int i = 0; i < n; i++) { if (!check[i]) { root = i; break; } } } return root; }
bool Isomorphic(ArrTree* AT1, ArrTree* AT2, int ATR1, int ATR2){ if (ATR1 == -1 && ATR2 == -1) return true; if ((ATR1 == -1 && ATR2 == -1) || ATR1 != -1 && ATR2 == -1) return false; if (AT1[ATR1].left == -1 && AT2[ATR2].left == -1) return Isomorphic(AT1, AT2, AT1[ATR1].right, AT2[ATR2].right); if ((AT1[ATR1].left != -1 && AT2[ATR2].left != -1) && (AT1[AT1[ATR1].left].data == AT2[AT2[ATR2].left].data)) return (Isomorphic(AT1, AT2, AT1[ATR1].left, AT2[ATR2].left) && Isomorphic(AT1, AT2, AT1[ATR1].right, AT2[ATR2].right)); else return (Isomorphic(AT1, AT2, AT1[ATR1].left, AT2[ATR2].right) && Isomorphic(AT1, AT2, AT1[ATR1].right, AT2[ATR2].left)); }
|
没有被任何结点指向的结点即为根节点 示例
存在的结点为0 1 3 4
其中 0 3 4 有在数组中出现,而1没有出现,说明下标1的数组中存的即是根结点