VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-all-elements-of-given-linked-list-corresponds-to-a-downward-path-from-any-node-in-given-binary-tree/

⇱ Check if all elements of given Linked List corresponds to a downward path from any node in given Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if all elements of given Linked List corresponds to a downward path from any node in given Binary Tree

Last Updated : 23 Jul, 2025

Given a root of the Binary Tree and head of the Linked List, the task is to check if all the elements of the linked list corresponds to a downward path from any node in the given Binary Tree.

Examples:

Input: Tree in the image below, list = {3, 6, 8}

👁 Image


Output: Yes
Explanation: There exists a downward path in the given Binary Tree, having all the elements of the linked list in the same order.

Input: Tree in the image below, list = {1, 2, 5, 7}
 

👁 Image


Output: Yes

Approach: The given problem can be solved with the help of the DFS Traversal of the Binary tree. During the DFS traversal, if any node of the Binary Tree is equal to the head of the linked list, a recursive function isPathUntil() can be called to recursively check whether the other elements of the linked list also exist as a path from that node. If the complete linked list has been traversed, there exists a valid required path, hence return true. Otherwise, return false. Follow the steps below to solve the given problem:

  • Declare a function, say isSubPathUtil(root, head) , and perform the following steps in this function:
    • If the root is NULL, then return false.
    • If the head is NULL, then return true.
    • If the value of the current root node is the same as the value of the current head of LL, then recursively call for isSubPathUtil(root->left, head->next) and isSubPathUtil(root->right, head->next) and if the value returned one of these recursive calls is true, then return true. Otherwise, return false.
  • Declare a function, say isSubPath(root, head), and perform the following steps in this function:
    • If the root is NULL, then return false.
    • If the head is NULL, then return true.
    • If the value of the current root node is the same as the value of the current head of LL, then recursively call for isSubPath(root->left, head->next) and isSubPath(root->right, head->next) and if the value returned one of these recursive calls is true, then return true. Otherwise, return value call recursively for isSubPath(root->left, head) and isSubPath(root->right, head).
  • After the above steps, if the value returned by the function isSubPath(root, head) is true , then print Yes . Otherwise, print No .

Below is the implementation of the above approach:


Output: 
Yes

 

Time Complexity: O(N * M) where N = Number of nodes in the Binary Tree and M = Number of nodes in the Linked list.
Auxiliary Space: O(height of the tree)

Comment