Magicsheet logo

Linked List in Binary Tree

Medium
100%
Updated 6/1/2025

Linked List in Binary Tree

What is this problem about?

The "Linked List in Binary Tree interview question" asks you to determine if a given linked list is present as a downward path in a binary tree. A "downward path" means you start at some node in the tree and follow only child pointers (left or right) such that the sequence of values matches the linked list. This "Linked List in Binary Tree coding problem" combines two fundamental data structures in a single task.

Why is this asked in interviews?

Companies like Google and Bloomberg use this to test a candidate's proficiency with "Depth-First Search interview pattern" and recursion across different data structures. It evaluates whether you can correctly handle the "start from any node" constraint and the "match a specific sequence" constraint simultaneously.

Algorithmic pattern used

The solution involves two recursive functions. The first function traverses every node in the binary tree (standard DFS). For each node, it calls a second "matching" function. The matching function checks if the current tree node matches the current linked list node. If it does, it recursively checks both the left and right children against the next linked list node.

Example explanation

List: 4 -> 2 -> 8 Tree: 1 -> Left(4 -> Left(2 -> Left(1), Right(8))), Right(4)

  1. The outer DFS finds the first '4' in the tree.
  2. The matching function starts. Tree(4) matches List(4).
  3. Check Tree children (2) against List next (2). Matches.
  4. Check Tree children (8) against List next (8). Matches.
  5. List end reached. Result: True.

Common mistakes candidates make

  • Inefficient recursion: Not realizing that every node in the tree can be a potential starting point for the list.
  • Missing branches: Only checking the left child or the right child instead of exploring both for a potential match.
  • Base case errors: Returning false prematurely when the list still has nodes left but the tree branch ends.

Interview preparation tip

This is a "DFS within a DFS" problem. Practice these types of nested recursions, as they are common when searching for patterns (like strings or lists) within larger structures (like trees or grids).

Similar Questions