C++ solution using post order traverse and serialization


  • 0
    A
    class Solution {
    public:
        string helper(vector<TreeNode *> &ans, unordered_map<string, int> &m, TreeNode *curr) {
            if (!curr)
                return "#";
            
            string left = helper(ans, m, curr->left), right = helper(ans, m, curr->right);
            string s = to_string(curr->val) + "," + left + "," + right;
            if (m[s] == 1)
                ans.push_back(curr);
            ++m[s];
            return s;
        }
        
        vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
            vector<TreeNode *> ans;
            unordered_map<string, int> m;
            helper(ans, m, root);
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.