lurenaa的博客

😔失败1

  不可以重载map的比较函数,因为map的实现是红黑树,用于红黑树排序比较。

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
#include <memory>
#include <iostream>
#include <vector>
#include <map>
using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
struct Cmp {
bool compr(const TreeNode* lhs, const TreeNode* rhs) const {
if (!lhs && !rhs)
return true;
if ((!lhs && rhs) || (lhs && !rhs))
return false;
bool v = lhs->val == rhs->val;
if (!v)
return false;
bool v1 = compr(lhs->left, rhs->left);
if (!v1)
return false;
bool v2 = compr(lhs->right, rhs->right);
if (!v2)
return false;
}
bool operator()(const TreeNode* lhs, const TreeNode* rhs) const {
return compr(lhs, rhs);
}
};
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
map<TreeNode*, int, Cmp> st;
vector<TreeNode*> vec;
dg(root, st, vec);
return vec;
}
void dg(TreeNode* h, map<TreeNode*, int, Cmp>& st, vector<TreeNode*>& vec)
{
if (!h)
return;
dg(h->left, st, vec);
dg(h->right, st, vec);
size_t ct = st.count(h);
if (ct > 0) {
if (st.at(h) == 1) {
cout << "i" << endl;
vec.push_back(h);
}
st.at(h) += 1;
cout << "t" << endl;
}
else {
st.insert({ h, 1 });
cout << "f" << endl;
}
}
};
int main()
{
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->right->left = new TreeNode(2);
root->right->right = new TreeNode(4);
root->right->left->left = new TreeNode(4);
Solution().findDuplicateSubtrees(root);
}

😍序列化

  序列化成字符串之后再来比较。

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
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
map<string, int> st;
vector<TreeNode*> vec;
string s;
dg(root, st, vec, s);
return vec;
}
void dg(TreeNode* h, map<string, int>& st, vector<TreeNode*>& vec, string& s)
{
if(!h)
return ;
dg(h->left, st, vec, s);
dg(h->right, st, vec, s);
s.clear();
seril(h, s);
if(st.count(s)) {
if(st.at(s) == 1) {
// cout << "i" << endl;
vec.push_back(h);
}
st.at(s) += 1;
// cout << "t" << endl;
} else {
st.insert({s, 1});
// cout << "f" << endl;
}
}
void seril(TreeNode* h,string& s)
{
if(!h) {
s += "@#";
return ;
}
s += to_string(h->val) + '#';
seril(h->left, s);
seril(h->right, s);
}
};

Accepted

168/168 cases passed (684 ms)

Your runtime beats 5.25 % of cpp submissions

Your memory usage beats 15.17 % of cpp submissions (54.5 MB)