-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0572_isSubtree.cc
135 lines (127 loc) · 2.58 KB
/
Problem_0572_isSubtree.cc
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <string>
#include <vector>
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) {}
};
class Solution
{
public:
// 暴力递归
// 时间复杂度O(n * m)
bool isSubtree1(TreeNode* root, TreeNode* subRoot)
{
if (root != nullptr && subRoot != nullptr)
{
return same(root, subRoot) || isSubtree1(root->left, subRoot) ||
isSubtree1(root->right, subRoot);
}
return subRoot == nullptr;
}
// 判断a和b这两棵树是否完全一样
bool same(TreeNode* a, TreeNode* b)
{
if (a == nullptr && b == nullptr)
{
return true;
}
if (a != nullptr && b != nullptr)
{
return a->val == b->val && same(a->left, b->left) && same(a->right, b->right);
}
return false;
}
// 二叉树先序序列化 + KMP算法匹配
// 时间复杂度O(n + m)
bool isSubtree2(TreeNode* root, TreeNode* subRoot)
{
if (root != nullptr && subRoot != nullptr)
{
vector<string> s1;
vector<string> s2;
serial(root, s1);
serial(subRoot, s2);
return kmp(s1, s2) != -1;
}
return subRoot == nullptr;
}
void serial(TreeNode* head, vector<string>& path)
{
if (head == nullptr)
{
path.push_back(",");
}
else
{
path.push_back(std::to_string(head->val));
serial(head->left, path);
serial(head->right, path);
}
}
int kmp(vector<string>& s, vector<string>& m)
{
if (s.size() < m.size())
{
return -1;
}
if (m.size() == 0)
{
return 0;
}
int x = 0;
int y = 0;
vector<int> next = getNextArray(m);
while (x < s.size() && y < m.size())
{
if (s[x] == m[y])
{
x++;
y++;
}
else if (next[y] == -1)
{
x++;
}
else
{
y = next[y];
}
}
return y == m.size() ? x - y : -1;
}
vector<int> getNextArray(vector<string>& ms)
{
if (ms.size() == 1)
{
return {-1};
}
vector<int> next(ms.size());
next[0] = -1;
next[1] = 0;
int i = 2;
// cn代表,cn位置的字符,是当前和i-1位置比较的字符
int cn = 0;
while (i < next.size())
{
if (ms[i - 1] == ms[cn])
{
next[i++] = ++cn;
}
else if (cn > 0)
{
cn = next[cn];
}
else
{
next[i++] = 0;
}
}
return next;
}
};