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}
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}
Â
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:
C++
// C++ program for the above approach Â
#include "bits/stdc++.h" using namespace std; Â
// Node of the Linked list struct listNode { Â Â Â Â int val; Â Â Â Â struct listNode* next; Â
    // Constructor     listNode( int data)     {         this ->val = data;         next = NULL;     } }; Â
// Node of the Binary Search tree struct treeNode { Â Â Â Â int val; Â Â Â Â treeNode* right; Â Â Â Â treeNode* left; Â
    // Constructor     treeNode( int data)     {         this ->val = data;         this ->left = NULL;         this ->right = NULL;     } }; Â
// Recursive function to check if there // exist a path from the node curTree // having the LL from the node curList bool isPathUtil(listNode* curList,                 treeNode* curTree) {     // If the complete linked list     // is traversed     if (curList == NULL)         return true ; Â
    // If the tree node doesnot exist     if (curTree == NULL)         return false ; Â
    if (curList->val == curTree->val) { Â
        // Recursively calling for the         // next element         return isPathUtil(curList->next,                           curTree->left)                || isPathUtil(curList->next,                              curTree->right);     }     else { Â
        // If not found, return false         return false ;     } } Â
// Function to check if the linked list // exist as a downward path in Binary tree // using the DFS Traversal of the Tree bool isPath(listNode* head, treeNode* root) { Â
    // If the current node of the     // tree is Null     if (root == NULL)         return false ; Â
    // If the complete linked list     // has been found     if (head == NULL)         return true ; Â
    // Stores if there exist the     // required path     bool isPossible = false ; Â
    if (root->val == head->val) { Â
        // Recursively calling to         // check the next node of         // the linked list         isPossible = isPathUtil(                          head->next, root->left)                      || isPathUtil(                             head->next, root->right);     } Â
    // Recursive calling for the next     // elements of the binary tree     return isPossible || isPath(head, root->left)            || isPath(head, root->right); } Â
// Driver Code int main() { Â Â Â Â treeNode* root = new treeNode(1); Â Â Â Â root->left = new treeNode(2); Â Â Â Â root->right = new treeNode(3); Â Â Â Â root->left->left = new treeNode(4); Â Â Â Â root->left->right = new treeNode(5); Â Â Â Â root->left->right->left = new treeNode(7); Â Â Â Â root->right->right = new treeNode(6); Â Â Â Â root->right->right->left = new treeNode(8); Â Â Â Â root->right->right->right = new treeNode(9); Â
    listNode* head = new listNode(3);     head->next = new listNode(6);     head->next->next = new listNode(8); Â
    // Function Call     cout << (isPath(head, root) ? "Yes" : "No" ); Â
    return 0; } |
Java
// Java program for the above approach Â
//include "bits/stdJava.h" import java.util.*; Â
public class GFG{ Â
// Node of the Linked list static class listNode { Â Â Â Â int val; Â Â Â Â listNode next; Â
    // Constructor     listNode( int data)     {         this .val = data;         next = null ;     } }; Â
// Node of the Binary Search tree static class treeNode { Â Â Â Â int val; Â Â Â Â treeNode right; Â Â Â Â treeNode left; Â
    // Constructor     treeNode( int data)     {         this .val = data;         this .left = null ;         this .right = null ;     } }; Â
// Recursive function to check if there // exist a path from the node curTree // having the LL from the node curList static boolean isPathUtil(listNode curList,                 treeNode curTree) {     // If the complete linked list     // is traversed     if (curList == null )         return true ; Â
    // If the tree node doesnot exist     if (curTree == null )         return false ; Â
    if (curList.val == curTree.val) { Â
        // Recursively calling for the         // next element         return isPathUtil(curList.next,                           curTree.left)                || isPathUtil(curList.next,                              curTree.right);     }     else { Â
        // If not found, return false         return false ;     } } Â
// Function to check if the linked list // exist as a downward path in Binary tree // using the DFS Traversal of the Tree static boolean isPath(listNode head, treeNode root) { Â
    // If the current node of the     // tree is Null     if (root == null )         return false ; Â
    // If the complete linked list     // has been found     if (head == null )         return true ; Â
    // Stores if there exist the     // required path     boolean isPossible = false ; Â
    if (root.val == head.val) { Â
        // Recursively calling to         // check the next node of         // the linked list         isPossible = isPathUtil(                          head.next, root.left)                      || isPathUtil(                             head.next, root.right);     } Â
    // Recursive calling for the next     // elements of the binary tree     return isPossible || isPath(head, root.left)            || isPath(head, root.right); } Â
// Driver Code public static void main(String[] args) { Â Â Â Â treeNode root = new treeNode( 1 ); Â Â Â Â root.left = new treeNode( 2 ); Â Â Â Â root.right = new treeNode( 3 ); Â Â Â Â root.left.left = new treeNode( 4 ); Â Â Â Â root.left.right = new treeNode( 5 ); Â Â Â Â root.left.right.left = new treeNode( 7 ); Â Â Â Â root.right.right = new treeNode( 6 ); Â Â Â Â root.right.right.left = new treeNode( 8 ); Â Â Â Â root.right.right.right = new treeNode( 9 ); Â
    listNode head = new listNode( 3 );     head.next = new listNode( 6 );     head.next.next = new listNode( 8 ); Â
    // Function Call     System.out.print((isPath(head, root) ? "Yes" : "No" )); Â
} } Â
// This code is contributed by 29AjayKumar |
Python3
# Python program for the above approach Â
# Node of the Linked list class listNode: Â
  # Constructor   def __init__ ( self , data):     self .val = data;     self . next = None ; Â
# Node of the Binary Search tree class treeNode: Â
  # Constructor   def __init__ ( self , data):     self .val = data;     self .left = None ;     self .right = None ;    # Recursive function to check if there # exist a path from the node curTree # having the LL from the node curList def isPathUtil(curList, curTree): Â
  # If the complete linked list   # is traversed   if (curList = = None ): return True ; Â
  # If the tree node doesnot exist   if (curTree = = None ): return False ; Â
  if (curList.val = = curTree.val):        # Recursively calling for the     # next element     return (       isPathUtil(curList. next , curTree.left) or       isPathUtil(curList. next , curTree.right)     );      else :        # If not found, return false     return False ;    # Function to check if the linked list # exist as a downward path in Binary tree # using the DFS Traversal of the Tree def isPath(head, root): Â
  # If the current node of the   # tree is None   if (root = = None ): return False ; Â
  # If the complete linked list   # has been found   if (head = = None ): return True ; Â
  # Stores if there exist the   # required path   isPossible = False ; Â
  if (root.val = = head.val):     # Recursively calling to     # check the next node of     # the linked list     isPossible = isPathUtil(head. next , root.left) or isPathUtil(head. next , root.right);    Â
  # Recursive calling for the next   # elements of the binary tree   return isPossible or isPath(head, root.left) or isPath(head, root.right); Â
Â
# Driver Code Â
root = treeNode( 1 ); root.left = treeNode( 2 ); root.right = treeNode( 3 ); root.left.left = treeNode( 4 ); root.left.right = treeNode( 5 ); root.left.right.left = treeNode( 7 ); root.right.right = treeNode( 6 ); root.right.right.left = treeNode( 8 ); root.right.right.right = treeNode( 9 ); Â
head = listNode( 3 ); head. next = listNode( 6 ); head. next . next = listNode( 8 ); Â
# Function Call print ( "Yes" if isPath(head, root) else "No" ); Â
# This code is contributed by saurabh_jaiswal. |
C#
// C# program for the above approach Â
//include "bits/stdJava.h" using System; Â
public class GFG{ Â
// Node of the Linked list class listNode { Â Â Â Â public int val; Â Â Â Â public listNode next; Â
    // Constructor     public listNode( int data)     {         this .val = data;         next = null ;     } }; Â
// Node of the Binary Search tree class treeNode { Â Â Â Â public int val; Â Â Â Â public treeNode right; Â Â Â Â public treeNode left; Â
    // Constructor     public treeNode( int data)     {         this .val = data;         this .left = null ;         this .right = null ;     } }; Â
// Recursive function to check if there // exist a path from the node curTree // having the LL from the node curList static bool isPathUtil(listNode curList,                 treeNode curTree) {     // If the complete linked list     // is traversed     if (curList == null )         return true ; Â
    // If the tree node doesnot exist     if (curTree == null )         return false ; Â
    if (curList.val == curTree.val) { Â
        // Recursively calling for the         // next element         return isPathUtil(curList.next,                           curTree.left)                || isPathUtil(curList.next,                              curTree.right);     }     else { Â
        // If not found, return false         return false ;     } } Â
// Function to check if the linked list // exist as a downward path in Binary tree // using the DFS Traversal of the Tree static bool isPath(listNode head, treeNode root) { Â
    // If the current node of the     // tree is Null     if (root == null )         return false ; Â
    // If the complete linked list     // has been found     if (head == null )         return true ; Â
    // Stores if there exist the     // required path     bool isPossible = false ; Â
    if (root.val == head.val) { Â
        // Recursively calling to         // check the next node of         // the linked list         isPossible = isPathUtil(                          head.next, root.left)                      || isPathUtil(                             head.next, root.right);     } Â
    // Recursive calling for the next     // elements of the binary tree     return isPossible || isPath(head, root.left)            || isPath(head, root.right); } Â
// Driver Code public static void Main(String[] args) { Â Â Â Â treeNode root = new treeNode(1); Â Â Â Â root.left = new treeNode(2); Â Â Â Â root.right = new treeNode(3); Â Â Â Â root.left.left = new treeNode(4); Â Â Â Â root.left.right = new treeNode(5); Â Â Â Â root.left.right.left = new treeNode(7); Â Â Â Â root.right.right = new treeNode(6); Â Â Â Â root.right.right.left = new treeNode(8); Â Â Â Â root.right.right.right = new treeNode(9); Â
    listNode head = new listNode(3);     head.next = new listNode(6);     head.next.next = new listNode(8); Â
    // Function Call     Console.Write((isPath(head, root) ? "Yes" : "No" )); Â
} } Â
// This code is contributed by 29AjayKumar |
Javascript
<script> // Javascript program for the above approach Â
// Node of the Linked list class listNode { Â
  // Constructor   constructor(data) {     this .val = data;     this .next = null ;   } } Â
// Node of the Binary Search tree class treeNode { Â
  // Constructor   constructor(data) {     this .val = data;     this .left = null ;     this .right = null ;   } } Â
// Recursive function to check if there // exist a path from the node curTree // having the LL from the node curList function isPathUtil(curList, curTree) { Â
  // If the complete linked list   // is traversed   if (curList == null ) return true ; Â
  // If the tree node doesnot exist   if (curTree == null ) return false ; Â
  if (curList.val == curTree.val)   {        // Recursively calling for the     // next element     return (       isPathUtil(curList.next, curTree.left) ||       isPathUtil(curList.next, curTree.right)     );   }   else   {        // If not found, return false     return false ;   } } Â
// Function to check if the linked list // exist as a downward path in Binary tree // using the DFS Traversal of the Tree function isPath(head, root) { Â
  // If the current node of the   // tree is null   if (root == null ) return false ; Â
  // If the complete linked list   // has been found   if (head == null ) return true ; Â
  // Stores if there exist the   // required path   let isPossible = false ; Â
  if (root.val == head.val) {     // Recursively calling to     // check the next node of     // the linked list     isPossible =       isPathUtil(head.next, root.left) || isPathUtil(head.next, root.right);   } Â
  // Recursive calling for the next   // elements of the binary tree   return isPossible || isPath(head, root.left) || isPath(head, root.right); } Â
// Driver Code Â
let root = new treeNode(1); root.left = new treeNode(2); root.right = new treeNode(3); root.left.left = new treeNode(4); root.left.right = new treeNode(5); root.left.right.left = new treeNode(7); root.right.right = new treeNode(6); root.right.right.left = new treeNode(8); root.right.right.right = new treeNode(9); Â
let head = new listNode(3); head.next = new listNode(6); head.next.next = new listNode(8); Â
// Function Call document.write(isPath(head, root) ? "Yes" : "No" ); Â
// This code is contributed by saurabh_jaiswal. </script> |
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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!