652. Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { unordered_map<string, vector<TreeNode*>> m; string search(TreeNode* node) { if(!node) return ""; string key = '(' + search(node->left) + '#' + to_string(node->val) + '#' + search(node->right) + ')'; m[key].push_back(node); return key; } public: vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { search(root); vector<TreeNode*> res; for(auto [key, values] : m) { if(values.size() > 1) res.push_back(values[0]); }
return res; } };
|