https://leetcode.com/problems/find-duplicate-subtrees/description/
class Solution {
public:
string dfs(TreeNode* root, vector<TreeNode*> &ans, unordered_map<string, TreeNode*>&mem, unordered_set<string> &get) {
if (!root) return "NULL";
string cur = to_string(root->val);
cur += dfs(root->left, ans, mem, get);
cur += dfs(root->right, ans, mem, get);
if (mem.find(cur) != mem.end()) {
if (get.find(cur) == get.end()) {
ans.push_back(root);
get.insert(cur);
}
} else {
mem[cur] = root;
}
return cur;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
vector<TreeNode*> ans;
unordered_set<string> tmp;
unordered_map<string, TreeNode*> mem;
dfs(root, ans, mem, tmp);
return ans;
}
};