Open In App

Check if there is a root to leaf path with given sequence

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree and an array, the task is to find if the given array sequence is present as a root-to-leaf path in given tree.

 

 Examples :

Input : arr[] = {5, 2, 4, 8} for above tree
Output: "Path Exist"

Input :  arr[] = {5, 3, 4, 9} for above tree
Output: "Path does not Exist"

A simple solution for this problem is to find all root-to-leaf paths in given tree and for each root-to-leaf path check whether path and given sequence in array both are identical or not.

An efficient solution for this problem is to traverse the tree once and while traversing the tree we have to check if path from root to current node is identical to the given sequence of root to leaf path. 

Algorithm:

  • Start traversing tree in preorder fashion.
  • Whenever we moves down in tree then we also move by one index in given sequence of root to leaf path .
  • If current node is equal to the arr[index] this means that till this level of tree path is identical.
  • Now remaining path will either be in left subtree or in right subtree.
  • If any node gets mismatched with arr[index] this means that current path is not identical to the given sequence of root to leaf path, so we return back and move in right subtree.
  • Now when we are at leaf node and it is equal to arr[index] and there is no further element in given sequence of root to leaf path, this means that path exist in given tree.

C++




// C++ program to see if there is a root to leaf path
// with given sequence.
#include<bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
    int data;
    struct Node* left, *right;
};
  
/* utility that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
  
// Util function
bool existPathUtil(struct Node *root, int arr[], int n, int index)
{
    // If root is NULL or reached end of the array
    if(root == NULL or index==n) 
            return false
  
    // If current node is leaf
    if (root->left == NULL && root->right == NULL)
    {
        if((root->data == arr[index]) && (index == n-1)) 
            return true
         
       return false;
    
  
    // If current node is equal to arr[index] this means
    // that till this level path has been matched and
    // remaining path can be either in left subtree or
    // right subtree.
    return ((index < n) && (root->data == arr[index]) &&
                (existPathUtil(root->left, arr, n, index+1) ||
                existPathUtil(root->right, arr, n, index+1) ));
}
  
// Function to check given sequence of root to leaf path exist
// in tree or not.
// index represents current element in sequence of rooth to
// leaf path
bool existPath(struct Node *root, int arr[], int n, int index)
{
    if(!root)
        return (n==0);
          
    return existPathUtil(root, arr, n, 0);
}
  
// Driver function to run the case
int main()
{
    // arr[] --> sequence of root to leaf path
    int arr[] = {5, 8, 6, 7};
    int n = sizeof(arr)/sizeof(arr[0]);
    struct Node *root = newnode(5);
    root->left = newnode(3);
    root->right = newnode(8);
    root->left->left = newnode(2);
    root->left->right = newnode(4);
    root->left->left->left = newnode(1);
    root->right->left = newnode(6);
    root->right->left->right = newnode(7);
  
    existPath(root, arr, n, 0)? cout << "Path Exists" :
                                cout << "Path does not Exist";
    return 0;
}


Java




// Java program to see if there is a root to leaf path
// with given sequence.
import java.io.*;
  
class Node
{
    int data;
    Node left;
    Node right;
      
    Node(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
  
  
class GFG {
      
    // Util function
    static boolean existPathUtil(Node root, int arr[], 
                        int n, int index)
    {
        // If root is NULL or 
        // reached end of the array
        if(root == null || index==n) 
                return false
       
        // If current node is leaf
        if (root.left == null && 
                        root.right == null)
        {
            if((root.data == arr[index]) && 
                                (index == n-1)) 
                return true
              
           return false;
        
       
        // If current node is equal to arr[index] this means
        // that till this level path has been matched and
        // remaining path can be either in left subtree or
        // right subtree.
        return ((index < n) && (root.data == arr[index]) 
            &&  (existPathUtil(root.left, arr, n, index+1)
            || existPathUtil(root.right, arr, n, index+1) ));
    }
       
    // Function to check given sequence of root 
    // to leaf path exist in tree or not.
    // index : current element in sequence of root to
    // leaf path
    static boolean existPath(Node root, int arr[], 
                                    int n, int index)
    {
        if(root == null)
            return (n==0);
               
        return existPathUtil(root, arr, n, 0);
    }
  
      
    public static void main (String[] args) {
          
    // arr[] : sequence of root to leaf path
    int arr[] = {5, 8, 6, 7};
    int n = arr.length;
    Node root = new Node(5);
    root.left = new Node(3);
    root.right = new Node(8);
    root.left.left = new Node(2);
    root.left.right = new Node(4);
    root.left.left.left = new Node(1);
    root.right.left = new Node(6);
    root.right.left.right = new Node(7);
   
    if(existPath(root, arr, n, 0))
        System.out.println("Path Exists");
    else
        System.out.println("Path does not Exist");
          
    }
}


Python3




# Python program to see if
# there is a root to leaf path
# with given sequence
  
# Class of Node
class Node:
      
    # Constructor to create a 
    # node in Binary Tree
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
   
# Util function   
def existPathUtil(root, arr, n, index):
      
    # If root is NULL or reached 
    # end of the array
    if not root or index == n:
        return False
      
    # If current node is leaf
    if not root.left and not root.right:
        if root.val == arr[index] and index == n-1:
            return True
        return False
      
    # If current node is equal to arr[index] this means
    # that till this level path has been matched and
    # remaining path can be either in left subtree or
    # right subtree.
    return ((index < n) and (root.val == arr[index]) and \
            (existPathUtil(root.left, arr, n, index+1) or \
            existPathUtil(root.right, arr, n, index+1)))
  
# Function to check given sequence of root to leaf path exist
# in tree or not.
# index represents current element in sequence of rooth to
# leaf path         
def existPath(root, arr, n, index):
    if not root:
        return (n == 0)
          
    return existPathUtil(root, arr, n, 0)
  
# Driver Code
if __name__ == "__main__":
    arr = [5, 8, 6, 7]
    n = len(arr)
    root = Node(5)
    root.left = Node(3)
    root.right = Node(8)
    root.left.left = Node(2)
    root.left.right = Node(4)
    root.left.left.left = Node(1)
    root.right.left = Node(6)
    root.right.left.right = Node(7)
      
    if existPath(root, arr, n, 0):
        print("Path Exists")
    else:
        print("Path does not Exist")


C#




// C# program to see if there
// is a root to leaf path 
// with given sequence. 
using System;
  
public class CheckForPath 
{
  
    // function to check given sequence
    // of root to leaf path exist 
    // in tree or not. 
    // index represents current element
    // in sequence of rooth to 
    // leaf path 
    public static bool existPath(Node root,
                        int []arr, int index)
    {
        // If root is NULL, then there
        // must not be any element 
        // in array. 
        if(root == null)
        {
            return arr.Length == 0;
        }
  
        // If this node is a leaf and matches with last entry 
        // of array. 
        if((root.left == null && root.right == null) && 
                                (root.data == arr[index] &&
                                root.data == arr[arr.Length - 1]))
        {
            return true;
        }
  
        // If current node is equal to arr[index] this means 
        // that till this level path has been matched and 
        // remaining path can be either in left subtree or 
        // right subtree. 
        return (index < arr.Length && (root.data == arr[index] && 
                       (existPath(root.left,arr,index + 1) || 
                        existPath(root.right, arr, index + 1))));
    }
      
    // Driver code
    public static void Main() 
    {
        // arr[] is sequence of root to leaf path 
        int []arr = {5, 8, 6, 7}; 
        Node root=new Node(5);
        root.left=new Node(3);
        root.right=new Node(8);
        root.left.left = new Node(2); 
        root.left.right = new Node(4); 
        root.left.left.left = new Node(1); 
        root.right.left = new Node(6); 
        root.right.left.right = new Node(7); 
  
        if(existPath(root, arr, 0))
        {
            Console.Write("Path Exists");
        }
        else
        {
            Console.Write("Path does not Exist");
        }
    
}
  
/* A binary tree node has data, 
pointer to left child and a
pointer to right child */
public class Node 
    public int data; 
    public Node left, right; 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
};
  
// This code is contributed Rajput-Ji 


Javascript




// JavaScript program to see if there is a root to leaf path
// with given sequence.
  
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
  
// Utility function
function existPathUtil(root, arr, n, index) {
    // If root is NULL or reached end of the array
    if (!root || index === n) return false;
  
    // If current node is leaf
    if (root.left === null && root.right === null) {
        if (root.data === arr[index] && index === n - 1) return true;
  
        return false;
    }
  
    // If current node is equal to arr[index] this means
    // that till this level path has been matched and
    // remaining path can be either in left subtree or
    // right subtree.
    return (
        index < n &&
        root.data === arr[index] &&
        (existPathUtil(root.left, arr, n, index + 1) ||
            existPathUtil(root.right, arr, n, index + 1))
    );
}
  
// Function to check given sequence of root to leaf path exist
// in tree or not.
// index represents current element in sequence of rooth to
// leaf path
function existPath(root, arr, n, index) {
    if (!root) return n === 0;
  
    return existPathUtil(root, arr, n, 0);
}
  
// Driver function to run the case
// arr[] --> sequence of root to leaf path
let arr = [5, 8, 6, 7];
let n = arr.length;
let root = new Node(5);
root.left = new Node(3);
root.right = new Node(8);
root.left.left = new Node(2);
root.left.right = new Node(4);
root.left.left.left = new Node(1);
root.right.left = new Node(6);
root.right.left.right = new Node(7);
  
existPath(root, arr, n, 0)
    ? console.log("Path Exists")
    : console.log("Path does not Exist");
  
// This code is contributed by adityamaharshi21


Output

Path Exists

Time Complexity: O(N), the time complexity of this algorithm is O(N), where N is the number of nodes in the tree. 
Auxiliary Space: O(h), where h is the height of the tree, this space is due to the recursive call stack.

 



Previous Article
Next Article

Similar Reads

Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Print all root to leaf paths with there relative positions
Given a binary tree, print the root to the leaf path, but add "_" to indicate the relative position. Example: Input : Root of below tree A / \ B C / \ / \ D E F G Output : All root to leaf paths _ _ A _ B D _ A B _ E A _ C F A _ C _ _ G Asked In: Google Interview The idea base on print path in vertical order. Below is complete algorithm : We do Pre
11 min read
Print the longest leaf to leaf path in a Binary tree
C/C++ Code // C++ program to print the longest leaf to leaf // path #include &lt;bits/stdc++.h&gt; using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node-&gt;data = data; node-&gt;left = node-&gt;right = NULL; return (node); }
15+ min read
Root to leaf path sum equal to a given number in BST
Given a BST and a number. The task is to check whether the given number is equal to the sum of all the node from root leaf across any of the root to leaf paths in the given Binary Search Tree. Approach: The idea is to traverse from root to all leaves in top-down fashion maintaining a path[] array to store current root to leaf path. While traversing
8 min read
Root to leaf path product equal to a given number
Given a binary tree and a number, the return is true if the tree has a root-to-leaf path such that the product of all the values along that path equals the given number. The return is false if no such path can be found. For example, in the above tree, there exist three roots to leaf paths with the following products. 240 –&gt; 10 – 8 – 3400 –&gt; 1
9 min read
Shortest root to leaf path sum equal to a given number
Given a binary tree and a number, the task is to return the length of the shortest path beginning at the root and ending at a leaf node such that the sum of numbers along that path is equal to ‘sum’. Print "-1" if no such path exists. Examples: Input: 1 / \ 10 15 / \ 5 2 Number = 16 Output: 2 There are two paths: 1-&gt;15, length of path is 3 1-
9 min read
Root to leaf path sum equal to a given number
Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found. Example: Input: 10 Sum = 23 / \ 8 2 / \ / 3 5 2 Output: True Explanation: Root to leaf path sum, existing in this tree are21 --&gt; 10 - 8 - 3 23 --
15+ min read
Print the first shortest root to leaf path in a Binary Tree
Given a Binary Tree with distinct values, the task is to print the first smallest root to leaf path. We basically need to print the leftmost root to leaf path that has the minimum number of nodes. Input: 1 / \ 2 3 / / \ 4 5 7 / \ \ 10 11 8 Output: 1 3 5 Input: 1 / \ 2 3 / / \ 40 5 7 \ 8 Output: 1 2 40 Approach: The idea is to use a queue to perform
12 min read
GCD from root to leaf path in an N-ary tree
Given an N-ary tree and an array val[] which stores the values associated with all the nodes. Also given are a leaf node X and N integers which denotes the value of the node. The task is to find the gcd of all the numbers in the node in the path between leaf to the root. Examples: Input: 1 / \ 2 3 / / \ 4 5 6 / \ 7 8 val[] = { -1, 6, 2, 6, 3, 4, 12
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg