/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
vector<TreeNode*> res;
if(root == NULL)
return res;
unordered_map<string, vector<TreeNode*>> map;
serialize(root, map);
for(auto it = map.begin(); it != map.end(); it++){
if(it->second.size() > 1){
res.push_back(it->second[0]);
}
}
return res;
}
string serialize(TreeNode *root, unordered_map<string, vector<TreeNode*>> &map){
if(root == NULL)
return "#";
string s = "(" + serialize(root->left, map) + to_string(root->val) + serialize(root->right, map) + ")";
map[s].push_back(root);
return s;
}
};
652. Find Duplicate Subtrees
最新推荐文章于 2020-11-11 15:09:00 发布