题目链接:https://leetcode.com/problems/find-duplicate-subtrees/description/
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1 / \ 2 3 / / \ 4 2 4 / 4
The following are two duplicate subtrees:
2 / 4
and
4
Therefore, you need to return above trees' root in the form of a list.
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string,vector<TreeNode*>> m;
vector<TreeNode*> dups;
serialize(root,m);
for(auto it=m.begin();it!=m.end();it++)
{
if(it->second.size()>1)
{
dups.push_back(it->second[0]);
}
}
return dups;
}
private:
string serialize(TreeNode* node,unordered_map<string,vector<TreeNode*>>& m)
{
if (!node) return "";
string s="("+serialize(node->left,m)+to_string(node->val)+serialize(node->right,m)+")";
m[s].push_back(node);
return s;
}
};
/**
* 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 {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
dfs(root);
return {repeat.begin(), repeat.end()};
}
string dfs(TreeNode* node) {
if (!node) {
return "";
}
string serial = to_string(node->val) + "(" + dfs(node->left) + ")(" + dfs(node->right) + ")";
auto it = seen.find(serial);
if ( it != seen.end()) {
repeat.insert(it->second);
}
else {
seen[serial] = node;
}
return serial;
}
private:
unordered_map<string, TreeNode*> seen;
unordered_set<TreeNode*> repeat;
};