[LeetCode] Find Duplicate Subtrees

652. Find Duplicate Subtrees

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

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
/**
* 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 {
unordered_map<string, vector<TreeNode*>> m;
string search(TreeNode* node) {
if(!node) return "";
string key = '(' + search(node->left) + '#' + to_string(node->val) + '#' + search(node->right) + ')';
m[key].push_back(node);
return key;
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
search(root);
vector<TreeNode*> res;
for(auto [key, values] : m) {
if(values.size() > 1)
res.push_back(values[0]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/find-duplicate-subtrees/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.