Problem Description
Given the head of a singly linked list and the root of a binary tree, determine if there exists a downward path in the tree (starting from any node and moving only to left or right children) that contains the nodes of the linked list in order.
Key Insights
- Use a DFS approach to traverse the binary tree starting at every node.
- For each tree node, initiate a matching process that compares the tree values with the linked list values.
- If the current tree node matches the current linked list node, recursively check if either the left or right child can match the next linked list node.
- The problem is similar to a “pattern matching” scenario where the pattern is the linked list and the text is the tree's downward path.
Space and Time Complexity
Time Complexity: O(N * L) where N is the number of nodes in the tree and L is the length of the linked list.
Space Complexity: O(H + L) where H is the height of the tree (recursion stack for tree traversal) and L is the maximum recursion depth for linked list matching.
Solution
We perform a DFS traversal on the binary tree. At each node, we check if we can start a matching process with the head of the linked list. The matching function uses recursion to verify if the current tree node matches the current linked list node and then continues to check if either subtree (left or right) can follow the next linked list node. If a complete match is found (i.e. the linked list becomes null), the function returns true, indicating that a downward path exists in the tree that matches the linked list.