<p>Given a binary tree <code>root</code> and a&nbsp;linked list with&nbsp;<code>head</code>&nbsp;as the first node.&nbsp;</p>

<p>Return True if all the elements in the linked list starting from the <code>head</code> correspond to some <em>downward path</em> connected in the binary tree&nbsp;otherwise return False.</p>

<p>In this context downward path means a path that starts at some node and goes downwards.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/02/12/sample_1_1720.png" style="width: 220px; height: 280px;" /></strong></p>

<pre>
<strong>Input:</strong> head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
<strong>Output:</strong> true
<strong>Explanation:</strong> Nodes in blue form a subpath in the binary Tree.  
</pre>

<p><strong class="example">Example 2:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/02/12/sample_2_1720.png" style="width: 220px; height: 280px;" /></strong></p>

<pre>
<strong>Input:</strong> head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no path in the binary tree that contains all the elements of the linked list from <code>head</code>.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree will be in the range <code>[1, 2500]</code>.</li>
	<li>The number of nodes in the list will be in the range <code>[1, 100]</code>.</li>
	<li><code>1 &lt;= Node.val&nbsp;&lt;= 100</code>&nbsp;for each node in the linked list and binary tree.</li>
</ul>

class Solution:
    def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
        # 将链表转化为数组
        def linked_list_to_array(head):
            arr = []
            while head:
                arr.append(head.val)
                head = head.next
            return arr

        # 构建部分匹配表（lps 数组）
        def build_lps(pattern):
            lps = [0] * len(pattern)
            length = 0  # 记录前缀的长度
            i = 1

            while i < len(pattern):
                if pattern[i] == pattern[length]:
                    length += 1
                    lps[i] = length
                    i += 1
                else:
                    if length != 0:
                        length = lps[length - 1]
                    else:
                        lps[i] = 0
                        i += 1
            return lps

        # KMP 搜索算法
        def kmp_search(text, pattern):
            lps = build_lps(pattern)
            i, j = 0, 0  # `i` 为 text 的指针，`j` 为 pattern 的指针

            while i < len(text):
                if text[i] == pattern[j]:
                    i += 1
                    j += 1

                if j == len(pattern):
                    return True  # 匹配成功
                elif i < len(text) and text[i] != pattern[j]:
                    if j != 0:
                        j = lps[j - 1]
                    else:
                        i += 1

            return False

        # 递归获取所有从根到叶子的路径
        def get_paths(node, current_path):
            if not node:
                return
            current_path.append(node.val)

            # 如果是叶子节点，检查路径
            if not node.left and not node.right:
                paths.append(list(current_path))
            else:
                # 递归左右子树
                if node.left:
                    get_paths(node.left, current_path)
                if node.right:
                    get_paths(node.right, current_path)

            # 回溯
            current_path.pop()

        # 获取链表和树的所有路径
        pattern = linked_list_to_array(head)
        paths = []
        get_paths(root, [])

        # 在每个路径中使用 KMP 搜索链表
        for path in paths:
            if kmp_search(path, pattern):
                return True

        return False

21100