Skip to content

Commit beec481

Browse files
committed
652. Find Duplicate Subtrees
1 parent 949bef5 commit beec481

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

find-duplicate-subtrees.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//Runtime: 32 ms
2+
class Solution {
3+
public:
4+
5+
string serialize(TreeNode* root, unordered_map<string, vector<TreeNode*> > &Mp)
6+
{
7+
if(!root)
8+
return "";
9+
10+
string s = "(" + serialize(root->left, Mp) + to_string(root->val) + serialize(root->right, Mp) + ")";
11+
Mp[s].push_back(root);
12+
return s;
13+
}
14+
15+
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
16+
vector<TreeNode* > res;
17+
unordered_map<string, vector<TreeNode* > > Mp;
18+
serialize(root, Mp);
19+
20+
for(auto it:Mp)
21+
{
22+
if(it.second.size() > 1)
23+
res.push_back(it.second[0]);
24+
}
25+
return res;
26+
}
27+
};

0 commit comments

Comments
 (0)