Talentd
FleetCode

1367. Linked List in Binary Tree

Medium52.1% acceptance5 companies

Given a binary tree root and a linked list with head as the first node. 

Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.

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

Example 1:

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.  

Example 2:

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: true

Example 3:

Input: 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.

Constraints:

  • The number of nodes in the tree will be in the range [1, 2500].
  • The number of nodes in the list will be in the range [1, 100].
  • 1 <= Node.val <= 100 for each node in the linked list and binary tree.

Hints open one at a time

Hint 1
Create recursive function, given a pointer in a Linked List and any node in the Binary Tree. Check if all the elements in the linked list starting from the head correspond to some downward path in the binary tree.
20:58
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for singly-linked list.
2# class ListNode:
3# def __init__(self, val=0, next=None):
4# self.val = val
5# self.next = next
6# Definition for a binary tree node.
7# class TreeNode:
8# def __init__(self, val=0, left=None, right=None):
9# self.val = val
10# self.left = left
11# self.right = right
12class Solution:
13 def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
14
Starter codePython 3Spaces: 4
Examples
Input
[4,2,8]
[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Input
[1,4,2,6]
[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Input
[1,4,2,6,8]
[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Your code is saved on this device.Solution