-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindDuplicateSubtrees.cpp
30 lines (27 loc) · 1 KB
/
FindDuplicateSubtrees.cpp
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
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
// not an efficient solution because string concatenation will take O(n^2) time
// O(n^2) for each concatenation + O(n) for traversal
string postOrder(TreeNode* root, unordered_map<string, int>& um, vector<TreeNode *>& res) {
if (root == nullptr) return "";
string s = to_string(root->val) + "," + postOrder(root->left, um, res) + "," + postOrder(root->right, um, res);
if(um[s]++ == 1) res.push_back(root);
return s;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
vector<TreeNode *> res;
unordered_map<string, int> um;
postOrder(root, um, res);
return res;
}
};