652. Find Duplicate Subtrees
1
/ \
2 3
/ / \
4 2 4
/
4 2
/
4 4// Preorder Traversal
string helper(TreeNode* node, unordered_map<string, int>& mp, vector<TreeNode*>& res) {
if (!node) return "#";
string str = to_string(node->val) + "," + helper(node->left, mp, res) + "," + helper(node->right, mp, res);
if (++mp[str] == 2) res.push_back(node);
return str;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { // time: O(n); space: O(n)
unordered_map<string, int> mp;
vector<TreeNode*> res;
helper(root, mp, res);
return res;
}Last updated