Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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;
- public:
- vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
- // Serialize the tree.
- serialize(root);
- // Check if two representations have count more than 1.
- // If so, add it to answer.
- vector<TreeNode*> res;
- for(auto p: m){
- if(p.second.size() > 1)
- res.push_back(p.second[0]);
- }
- return res;
- }
- string serialize(TreeNode *root){
- if(!root) return "#";
- // Get representation of current subtree.
- string repr = "";
- repr = to_string(root->val)+','+serialize(root->left)+','+serialize(root->right);
- // Add root to hash of current representaion.
- m[repr].push_back(root);
- return repr;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment