nikunjsoni

652

May 7th, 2021
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. unordered_map<string, vector<TreeNode*> > m;
  14. public:
  15.     vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
  16.         // Serialize the tree.
  17.         serialize(root);
  18.  
  19.         // Check if two representations have count more than 1.
  20.         // If so, add it to answer.
  21.         vector<TreeNode*> res;
  22.         for(auto p: m){
  23.             if(p.second.size() > 1)
  24.                 res.push_back(p.second[0]);
  25.         }
  26.         return res;
  27.     }
  28.    
  29.     string serialize(TreeNode *root){
  30.         if(!root) return "#";
  31.        
  32.         // Get representation of current subtree.
  33.         string repr = "";
  34.         repr = to_string(root->val)+','+serialize(root->left)+','+serialize(root->right);
  35.        
  36.         // Add root to hash of current representaion.
  37.         m[repr].push_back(root);
  38.         return repr;
  39.     }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment