-
Notifications
You must be signed in to change notification settings - Fork 1
/
652.寻找重复的子树.cpp
86 lines (79 loc) · 1.83 KB
/
652.寻找重复的子树.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
/*
* @lc app=leetcode.cn id=652 lang=cpp
*
* [652] 寻找重复的子树
*/
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
#include <sstream>
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) {}
};
// @lc code=start
/**
* Definition for a binary tree node.
* 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:
unordered_map<string, int> memo;
vector<TreeNode *> res;
vector<TreeNode *> findDuplicateSubtrees(TreeNode *root)
{
find(root);
return res;
}
string find(TreeNode *root)
{
if (root == nullptr)
return "#";
string left = find(root->left);
string right = find(root->right);
string subTree = left + "," + right + "," + int_string(root->val);
int freq = memo[subTree];
if (freq == 1)
{
res.push_back(root);
// cout << ">>>" << root->val;
}
memo[subTree] = freq + 1;
// cout << memo[subTree];
// cout << subTree << endl;
return subTree;
}
string int_string(int a)
{ //int转string
stringstream st;
st << a;
string str = st.str();
return str;
}
};
// @lc code=end
int main()
{
Solution s;
}
/**
*
in 431 432 4
先序遍历 124 324 4
后序 42 42 4 3 1
*/