Leetcode 1367: Linked List in Binary Tree

grid47
grid47
Exploring patterns and algorithms
Jun 23, 2024 6 min read

You are given a binary tree and a linked list. Determine if there exists a downward path in the binary tree that matches all elements of the linked list starting from its head node. A downward path means starting from any node in the binary tree and following child nodes downwards.
Problem
Approach
Steps
Complexity
Input: The input consists of a linked list and a binary tree. The linked list is represented as an array of values and the binary tree is represented as a root node of a binary tree structure.
Example: head = [4, 2, 8], root = [1, 4, 4, null, 2, 2, null, 1, null, 6, 8, null, null, null, null, 1, 3]
Constraints:
• The number of nodes in the binary tree will be in the range [1, 2500].
• The number of nodes in the linked list will be in the range [1, 100].
• 1 <= Node.val <= 100 for each node in both the linked list and binary tree.
Output: Return True if there exists a downward path in the binary tree that matches all elements of the linked list starting from its head node, otherwise return False.
Example: True
Constraints:
• The result will be a boolean value: True or False.
Goal: To determine if there exists a downward path in the binary tree that matches all elements of the linked list starting from the head node.
Steps:
• Perform a depth-first search (DFS) to check if the current node value matches the head of the linked list.
• If a match is found, recursively check the left and right child nodes to see if the subsequent linked list elements match the downward path.
• If no match is found at any step, return False.
Goal: Ensure the solution efficiently handles large inputs and follows the problem constraints.
Steps:
• The binary tree has at most 2500 nodes.
• The linked list has at most 100 nodes.
Assumptions:
• The binary tree and linked list contain valid values as per the problem constraints.
• The input tree and linked list are not null.
Input: head = [4, 2, 8], root = [1, 4, 4, null, 2, 2, null, 1, null, 6, 8, null, null, null, null, 1, 3]
Explanation: The linked list elements [4, 2, 8] correspond to a downward path starting from node 4, then node 2, and then node 8 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]
Explanation: The linked list elements [1, 4, 2, 6] form a valid downward path in the binary tree, matching the nodes from root down to 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus