Skip to content

Commit fe09b68

Browse files
committedMay 19, 2021
652
1 parent 827a530 commit fe09b68

File tree

2 files changed

+95
-1
lines changed

2 files changed

+95
-1
lines changed
 

‎.vscode/settings.json

+9-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@
66
"algorithm": "cpp",
77
"string": "cpp",
88
"queue": "cpp",
9-
"chrono": "cpp"
9+
"chrono": "cpp",
10+
"unordered_map": "cpp",
11+
"__functional_03": "cpp",
12+
"__string": "cpp",
13+
"deque": "cpp",
14+
"functional": "cpp",
15+
"system_error": "cpp",
16+
"*.tcc": "cpp",
17+
"array": "cpp"
1018
}
1119
}

‎652.寻找重复的子树.cpp

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* @lc app=leetcode.cn id=652 lang=cpp
3+
*
4+
* [652] 寻找重复的子树
5+
*/
6+
7+
#include <iostream>
8+
#include <vector>
9+
#include <unordered_map>
10+
#include <string>
11+
#include <sstream>
12+
using namespace std;
13+
struct TreeNode
14+
{
15+
int val;
16+
TreeNode *left;
17+
TreeNode *right;
18+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
19+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
20+
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
21+
};
22+
23+
// @lc code=start
24+
/**
25+
* Definition for a binary tree node.
26+
* struct TreeNode {
27+
* int val;
28+
* TreeNode *left;
29+
* TreeNode *right;
30+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
31+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
32+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
33+
* };
34+
*/
35+
class Solution
36+
{
37+
public:
38+
unordered_map<string, int> memo;
39+
vector<TreeNode *> res;
40+
vector<TreeNode *> findDuplicateSubtrees(TreeNode *root)
41+
{
42+
find(root);
43+
return res;
44+
}
45+
string find(TreeNode *root)
46+
{
47+
if (root == nullptr)
48+
return "#";
49+
50+
string left = find(root->left);
51+
string right = find(root->right);
52+
string subTree = left + "," + right + "," + int_string(root->val);
53+
54+
int freq = memo[subTree];
55+
if (freq == 1)
56+
{
57+
res.push_back(root);
58+
// cout << ">>>" << root->val;
59+
}
60+
memo[subTree] = freq + 1;
61+
// cout << memo[subTree];
62+
// cout << subTree << endl;
63+
return subTree;
64+
}
65+
string int_string(int a)
66+
{ //int转string
67+
stringstream st;
68+
st << a;
69+
string str = st.str();
70+
return str;
71+
}
72+
};
73+
// @lc code=end
74+
75+
int main()
76+
{
77+
Solution s;
78+
}
79+
/**
80+
*
81+
in 431 432 4
82+
先序遍历 124 324 4
83+
84+
后序 42 42 4 3 1
85+
86+
*/

0 commit comments

Comments
 (0)
Please sign in to comment.