1367. Linked List in Binary Tree
https://leetcode.com/problems/linked-list-in-binary-tree/


Last updated
https://leetcode.com/problems/linked-list-in-binary-tree/


Last updated
Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: true
Explanation: Nodes in blue form a subpath in the binary Tree. Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: trueInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: false
Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.class Solution {
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if (head == nullptr) return true;
if (root == nullptr) return false;
if (head->val == root->val) {
if (isSubPath(head->next, root->left) || isSubPath(head->next, root->right)) return true;
}
return isSubPath(head, root->left) || isSubPath(head, root->right);
}
};/**
* 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) {}
* };
*/
class Solution {
public:
bool isSubPath(ListNode *head, TreeNode *root) {
vector<int> A = {head->val}, dp = {0};
int ptr = 0;
head = head->next;
while (head) {
while (head && ptr && head->val != A[ptr]) ptr = dp[ptr - 1];
ptr += head->val == A[ptr];
A.push_back(head->val);
dp.push_back(ptr);
head = head->next;
}
return dfs(root, 0, A, dp);
}
bool dfs(TreeNode* root, int i, vector<int> &A, vector<int> &dp) {
if (!root) return false;
while (i && root->val != A[i]) i = dp[i - 1];
i += root->val == A[i];
return i == dp.size() || dfs(root->left, i, A, dp) || dfs(root->right, i, A, dp);
}
};