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
| #include <memory> #include <iostream> #include <vector> #include <map> using namespace std;
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: struct Cmp { bool compr(const TreeNode* lhs, const TreeNode* rhs) const { if (!lhs && !rhs) return true; if ((!lhs && rhs) || (lhs && !rhs)) return false; bool v = lhs->val == rhs->val; if (!v) return false; bool v1 = compr(lhs->left, rhs->left); if (!v1) return false; bool v2 = compr(lhs->right, rhs->right); if (!v2) return false; } bool operator()(const TreeNode* lhs, const TreeNode* rhs) const { return compr(lhs, rhs); } }; vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { map<TreeNode*, int, Cmp> st; vector<TreeNode*> vec; dg(root, st, vec); return vec; } void dg(TreeNode* h, map<TreeNode*, int, Cmp>& st, vector<TreeNode*>& vec) { if (!h) return; dg(h->left, st, vec); dg(h->right, st, vec); size_t ct = st.count(h); if (ct > 0) { if (st.at(h) == 1) { cout << "i" << endl; vec.push_back(h); } st.at(h) += 1; cout << "t" << endl; } else { st.insert({ h, 1 }); cout << "f" << endl; } } }; int main() { TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->right->left = new TreeNode(2); root->right->right = new TreeNode(4); root->right->left->left = new TreeNode(4); Solution().findDuplicateSubtrees(root); }
|