Find Duplicate Subtrees LeetCode solution in C++

1
class Solution {
2
public:
3
unordered_map<string, int> dp;
4
vector<TreeNode *> ans;
5

6
string solve(TreeNode *root) {
7
if (!root) return "";
8

9
string left = solve(root->left);
10
string right = solve(root->right);
11

12
string code = to_string(root->val) + " " + left + " " + right;
13
if (dp[code] == 1) ans.push_back(root);
14
dp[code]++;
15

16
return code;
17
}
18

19
vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) {
20
string dummy = solve(root);
21
return ans;
22
}
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0