-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathFind_Duplicate_Subtrees.cpp
93 lines (87 loc) · 2.85 KB
/
Find_Duplicate_Subtrees.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// AC
// postorder and preorder signature will work, inorder not.
class Solution {
string preorder(TreeNode* root, unordered_map<string, int>& preOrderMap, vector<TreeNode*>& result) {
if(!root) {
return "#";
}
signature += "," + to_string(root->val);
string signature = preorder(root->left, preOrderMap, result);
signature += "," + preorder(root->right, preOrderMap, result);
// signature += "," + to_string(root->val); would work too
if(preOrderMap[signature] == 1) {
result.push_back(root);
}
preOrderMap[signature]++;
return signature;
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
vector<TreeNode*> result;
unordered_map<string, int> preOrderMap;
preorder(root, preOrderMap, result);
return result;
}
};
// brute-force, TLE, 121/167 testcases passed
class Solution {
bool isSame(TreeNode* rootA, TreeNode* rootB) {
if(!rootA and !rootB) {
return true;
}
if(!rootA or !rootB) {
return false;
}
return rootA->val == rootB->val and isSame(rootA->left, rootB->left) and isSame(rootA->right, rootB->right);
}
bool hasDuplicate(TreeNode* node, TreeNode* root, unordered_set<TreeNode*>& visited) {
if(!root) {
return false;
}
if(visited.find(root) == visited.end() and isSame(node, root)) {
visited.insert(root);
return true;
}
int leftDuplicate = hasDuplicate(node, root->left, visited);
int rightDuplicate = hasDuplicate(node, root->right, visited);
return leftDuplicate or rightDuplicate;
}
void findDuplicateSubtrees(TreeNode* node, TreeNode* root, vector<TreeNode*>& result, unordered_set<TreeNode*>& visited) {
if(!node) {
return;
}
if(visited.find(node) == visited.end()) {
visited.insert(node);
if(hasDuplicate(node, root, visited)) {
result.push_back(node);
}
}
findDuplicateSubtrees(node->left, root, result, visited);
findDuplicateSubtrees(node->right, root, result, visited);
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_set<TreeNode*> visited;
vector<TreeNode*> result;
findDuplicateSubtrees(root, root, result, visited);
return result;
}
};