forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list-in-binary-tree.cpp
102 lines (96 loc) · 2.4 KB
/
linked-list-in-binary-tree.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Time: O(n + l)
// Space: O(h + l)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// kmp solution
class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if (!head) {
return true;
}
const auto& [pattern, prefix] = getPrefix(head);
return dfs(pattern, prefix, root, -1);
}
private:
bool dfs(const vector<int>& pattern,
const vector<int>& prefix,
TreeNode *root, int j) {
if (!root) {
return false;
}
while (j + 1 && pattern[j + 1] != root->val) {
j = prefix[j];
}
if (pattern[j + 1] == root->val) {
++j;
}
if (j + 1 == pattern.size()) {
return true;
}
return dfs(pattern, prefix, root->left, j) ||
dfs(pattern, prefix, root->right, j);
}
pair<vector<int>, vector<int>> getPrefix(ListNode *head) {
vector<int> pattern = {head->val};
vector<int> prefix = {-1};
int j = -1;
auto node = head->next;
while (node) {
while (j + 1 && pattern[j + 1] != node->val) {
j = prefix[j];
}
if (pattern[j + 1] == node->val) {
++j;
}
pattern.emplace_back(node->val);
prefix.emplace_back(j);
node = node->next;
}
return {pattern, prefix};
}
};
// Time: O(n * min(h, l))
// Space: O(h)
// dfs solution
class Solution2 {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if (!head) {
return true;
}
if (!root) {
return false;
}
return dfs(head, root) ||
isSubPath(head, root->left) ||
isSubPath(head, root->right);
}
private:
bool dfs(ListNode *head, TreeNode *root) {
if (!head) {
return true;
}
if (!root) {
return false;
}
return root->val == head->val &&
(dfs(head->next, root->left) ||
dfs(head->next, root->right));
}
};