Linked List in Binary Tree - Problem

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.

Input & Output

Example 1 — Path Found
$ Input: root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3], head = [4,2,8]
Output: true
💡 Note: The path 4→2→8 exists in the tree starting from the left node with value 4, going right to 2, then right to 8
Example 2 — Path Not Found
$ Input: root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3], head = [1,4,2,6]
Output: false
💡 Note: No downward path in the tree matches the sequence 1→4→2→6 from the linked list
Example 3 — Single Node Match
$ Input: root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3], head = [1]
Output: true
💡 Note: Single node 1 exists in the tree, so the path is found

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

Visualization

Tap to expand
Linked List in Binary Tree INPUT Binary Tree: 1 4 4 2 2 1 6 8 1 3 Linked List (head): 4 2 8 head = [4,2,8] ALGORITHM STEPS Optimized DFS 1 Start DFS from root Try matching list at each tree node encountered 2 Match check function If node matches head, check children with next list node 3 Recursive exploration Continue down left/right subtrees for path match 4 Return result True if list exhausted, false if mismatch found Found Path: 4 --> 2 --> 8 4 2 8 Match found in right subtree! FINAL RESULT OK Output: true The path 4 --> 2 --> 8 exists in the tree as a downward path Matching Path: 4 2 8 Key Insight: Use two recursive functions: one to traverse tree nodes as potential starting points, another to check if linked list matches downward path. Time: O(N*M), Space: O(H+L) for recursion. TutorialsPoint - Linked List in Binary Tree | Optimized DFS
Asked in
Microsoft 15 Amazon 12 Google 8 Facebook 6
28.0K Views
Medium Frequency
~25 min Avg. Time
985 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen