forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path652.find-duplicate-subtrees.cpp
More file actions
37 lines (30 loc) · 918 Bytes
/
652.find-duplicate-subtrees.cpp
File metadata and controls
37 lines (30 loc) · 918 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
string postOrderTraverse(vector<TreeNode *> &res, unordered_map<string, int> &map, TreeNode* node){
if (node == NULL){
return "#";
}
string s = to_string(node->val) + "(" + postOrderTraverse(res, map, node->left) + "," + postOrderTraverse(res, map, node->right) + ")" ;
if (map[s] == 1){
res.push_back(node);
}
map[s] += 1;
return s;
}
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
vector<TreeNode *> res;
unordered_map<string, int> map;
postOrderTraverse(res, map, root);
return res;
}
};