Description
Submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<TreeNode*> rets;
unordered_map<string, int> key2id;
unordered_map<int, int> id2cnt;
int getId(TreeNode* root) {
if(root == nullptr) return -1;
string cur = to_string(root->val) + "#" +
to_string(getId(root->left)) + "#" +
to_string(getId(root->right));
if(!key2id.count(cur)) key2id[cur] = key2id.size();
if(++id2cnt[key2id[cur]] == 2) {
rets.push_back(root);
}
return key2id[cur];
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
getId(root);
return rets;
}
};