Skip to content

Commit 4243e85

Browse files
authored
Create linked-list-in-binary-tree.cpp
1 parent 3637986 commit 4243e85

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

C++/linked-list-in-binary-tree.cpp

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Time: O(n + l)
2+
// Space: O(h + l)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
/**
13+
* Definition for a binary tree node.
14+
* struct TreeNode {
15+
* int val;
16+
* TreeNode *left;
17+
* TreeNode *right;
18+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
19+
* };
20+
*/
21+
22+
// kmp solution
23+
class Solution {
24+
public:
25+
bool isSubPath(ListNode* head, TreeNode* root) {
26+
if (!head) {
27+
return true;
28+
}
29+
const auto& [pattern, prefix] = getPrefix(head);
30+
return dfs(pattern, prefix, root, -1);
31+
}
32+
33+
private:
34+
bool dfs(const vector<int>& pattern,
35+
const vector<int>& prefix,
36+
TreeNode *root, int j) {
37+
if (!root) {
38+
return false;
39+
}
40+
while (j + 1 && pattern[j + 1] != root->val) {
41+
j = prefix[j];
42+
}
43+
if (pattern[j + 1] == root->val) {
44+
++j;
45+
}
46+
if (j + 1 == pattern.size()) {
47+
return true;
48+
}
49+
return dfs(pattern, prefix, root->left, j) ||
50+
dfs(pattern, prefix, root->right, j);
51+
}
52+
53+
pair<vector<int>, vector<int>> getPrefix(ListNode *head) {
54+
vector<int> pattern = {head->val};
55+
vector<int> prefix = {-1};
56+
int j = -1;
57+
auto node = head->next;
58+
while (node) {
59+
while (j + 1 && pattern[j + 1] != node->val) {
60+
j = prefix[j];
61+
}
62+
if (pattern[j + 1] == node->val) {
63+
++j;
64+
}
65+
pattern.emplace_back(node->val);
66+
prefix.emplace_back(j);
67+
node = node->next;
68+
}
69+
return {pattern, prefix};
70+
}
71+
};
72+
73+
// Time: O(n * min(h, l))
74+
// Space: O(h)
75+
// dfs solution
76+
class Solution2 {
77+
public:
78+
bool isSubPath(ListNode* head, TreeNode* root) {
79+
if (!head) {
80+
return true;
81+
}
82+
if (!root) {
83+
return false;
84+
}
85+
return dfs(head, root) ||
86+
isSubPath(head, root->left) ||
87+
isSubPath(head, root->right);
88+
}
89+
90+
private:
91+
bool dfs(ListNode *head, TreeNode *root) {
92+
if (!head) {
93+
return true;
94+
}
95+
if (!root) {
96+
return false;
97+
}
98+
return root->val == head->val &&
99+
(dfs(head->next, root->left) ||
100+
dfs(head->next, root->right));
101+
}
102+
};

0 commit comments

Comments
 (0)