Check if there is a root to leaf path with given sequence
Last Updated : 11 Oct, 2024
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}
Output: True Explanation: The given array sequence {5, 2, 4, 8} is present as a root-to-leaf path in given tree.
Input: arr = {5, 3, 4, 9}
Output: False Explanation: The given array sequence {5, 3, 4, 9} is not present as a root-to-leaf path in given tree.
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.
Approach:
The idea 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.
Below is the implementation of the above approach:
C++
// C++ code to check if the given array // sequence exists as a root-to-leaf path#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to check if the path existsboolcheckPath(Node*root,vector<int>&arr,intindex){// If root is NULL or index exceeds //array size, return falseif(!root||index>=arr.size()){returnfalse;}// If current node does not match the // array element, return falseif(root->data!=arr[index]){returnfalse;}// If we reach the leaf node and the // sequence matches fullyif(!root->left&&!root->right&&index==arr.size()-1){returntrue;}// Recurse for left and right subtrees by moving// to next index in arrreturncheckPath(root->left,arr,index+1)||checkPath(root->right,arr,index+1);}intmain(){// Representation of the given tree// 5// / \ // 2 3// / \ // 1 4// / \ // 6 8Node*root=newNode(5);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(1);root->left->right=newNode(4);root->left->right->left=newNode(6);root->left->right->right=newNode(8);vector<int>arr={5,2,4,8};if(checkPath(root,arr,0)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
Java
// Java code to check if the given array sequence// exists as a root-to-leaf path in a binary treeimportjava.util.ArrayList;importjava.util.Arrays;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Function to check if the path existsstaticbooleancheckPath(Noderoot,ArrayList<Integer>arr,intindex){// If root is null or index exceeds // array size, return falseif(root==null||index>=arr.size()){returnfalse;}// If current node does not match the // array element, return falseif(root.data!=arr.get(index)){returnfalse;}// If we reach the leaf node and the // sequence matches fullyif(root.left==null&&root.right==null&&index==arr.size()-1){returntrue;}// Recurse for left and right subtrees// by moving to next index in arrreturncheckPath(root.left,arr,index+1)||checkPath(root.right,arr,index+1);}// Function to check if the sequence existsstaticvoidisPathExist(Noderoot,ArrayList<Integer>arr){}publicstaticvoidmain(String[]args){// Representation of the given tree// 5// / \// 2 3// / \// 1 4// / \// 6 8Noderoot=newNode(5);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(1);root.left.right=newNode(4);root.left.right.left=newNode(6);root.left.right.right=newNode(8);ArrayList<Integer>arr=newArrayList<>(Arrays.asList(5,2,4,8));if(checkPath(root,arr,0)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python code to check if the given array sequence# exists as a root-to-leaf path in a binary treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to check if the path existsdefcheck_path(root,arr,index):# If root is None or index exceeds # array size, return Falseifnotrootorindex>=len(arr):returnFalse# If current node does not match the # array element, return Falseifroot.data!=arr[index]:returnFalse# If we reach the leaf node and the # sequence matches fullyifnotroot.leftandnotroot.right \
andindex==len(arr)-1:returnTrue# Recurse for left and right subtrees# by moving to next index in arrreturncheck_path(root.left,arr,index+1) \
orcheck_path(root.right,arr,index+1)if__name__=="__main__":# Representation of the given tree# 5# / \# 2 3# / \# 1 4# / \# 6 8root=Node(5)root.left=Node(2)root.right=Node(3)root.left.left=Node(1)root.left.right=Node(4)root.left.right.left=Node(6)root.left.right.right=Node(8)arr=[5,2,4,8]ifcheck_path(root,arr,0):print("True")else:print("False")
C#
// C# code to check if the given array sequence// exists as a root-to-leaf path in a binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Function to check if the path existsstaticboolCheckPath(Noderoot,List<int>arr,intindex){// If root is null or index exceeds// array size, return falseif(root==null||index>=arr.Count){returnfalse;}// If current node does not match // the array element, return falseif(root.data!=arr[index]){returnfalse;}// If we reach the leaf node and // the sequence matches fullyif(root.left==null&&root.right==null&&index==arr.Count-1){returntrue;}// Recurse for left and right subtrees by // moving to next index in arrreturnCheckPath(root.left,arr,index+1)||CheckPath(root.right,arr,index+1);}staticvoidMain(string[]args){// Representation of the given tree// 5// / \// 2 3// / \// 1 4// / \// 6 8Noderoot=newNode(5);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(1);root.left.right=newNode(4);root.left.right.left=newNode(6);root.left.right.right=newNode(8);List<int>arr=newList<int>{5,2,4,8};if(CheckPath(root,arr,0)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript code to check if the given array sequence// exists as a root-to-leaf path in a binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to check if the path existsfunctioncheckPath(root,arr,index){// If root is null or index exceeds// array size, return falseif(!root||index>=arr.length){returnfalse;}// If current node does not match the // array element, return falseif(root.data!==arr[index]){returnfalse;}// If we reach the leaf node and // the sequence matches fullyif(!root.left&&!root.right&&index===arr.length-1){returntrue;}// Recurse for left and right subtrees // by moving to next index in arrreturncheckPath(root.left,arr,index+1)||checkPath(root.right,arr,index+1);}// Representation of the given tree// 5// / \// 2 3// / \// 1 4// / \// 6 8constroot=newNode(5);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(1);root.left.right=newNode(4);root.left.right.left=newNode(6);root.left.right.right=newNode(8);constarr=[5,2,4,8];if(checkPath(root,arr,0)){console.log("True");}else{console.log("False");}
Output
True
Time Complexity: O(n), where n is the number of nodes in the tree. Auxiliary Space: O(h), due to the recursive call stack, where h is the height of the tree.