数据结构---0301树的同构

mac2026-04-11  4

**题目:**https://pintia.cn/problem-sets/1169812488801005568/problems/1179652789523730432 step1:

#include<iostream> #include<string> #define null -1 using namespace std; struct BiNode { char data; int left; int right; }T1[10],T2[10]; int create(struct BiNode T[]) { int n; cin >> n; char left, right; int root = 0; if (!n) { return null; } else { for (int i = 0;i < n;i++) { cin >> T[i].data >> left >> right; if (right == '-') { T[i].right = null; } else { T[i].right = right - '0'; root -= T[i].right; } if (left == '-') { T[i].left = null; } else { T[i].left = left - '0'; root -= T[i].left; } root += i; } } return root; } //如何判断同构 2 bool judge(int R1, int R2) { if (R1 == null && R2 == null) // 都为空 return true; if (R1 == null && R2 != null || R1 != null && R2 == null) // 一个为空,一个不为空 return false; if (T1[R1].data != T2[R2].data) // 值不同 return false; if ((T1[R1].left != null && T2[R2].left != null) && (T1[T1[R1].left].data == T2[T2[R2].left].data)) // 左儿子不为空且值相等 return judge(T1[R1].left, T2[R2].left) && judge(T1[R1].right, T2[R2].right); else // 左儿子不为空且值不等 或者 某一个左儿子为空 return judge(T1[R1].right, T2[R2].left) && judge(T1[R1].left, T2[R2].right); } int main() { int R1, R2; R1 = create(T1); R2 = create(T2); if (judge(R1, R2)) cout << "Yes"; else cout << "No"; return 0; }
最新回复(0)