Check if there is a root to leaf path with given sequence | C # program to see if there is a root to leaf path with given sequence . ; A binary tree node has data , pointer to left child and a pointer to right child ; 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 ; If root is NULL , then there must not be any element in array . ; If this node is a leaf and matches with last entry of array . ; 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 . ; Driver code ; arr [ ] is sequence of root to leaf path
using System ; public class CheckForPath { public class Node { public int data ; public Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } ; public static bool existPath ( Node root , int [ ] arr , int index ) { if ( root == null ) { return arr . Length == 0 ; } if ( ( root . left == null && root . right == null ) && ( root . data == arr [ index ] && root . data == arr [ arr . Length - 1 ] ) ) { return true ; } return ( index < arr . Length && ( root . data == arr [ index ] && ( existPath ( root . left , arr , index + 1 ) || existPath ( root . right , arr , index + 1 ) ) ) ) ; } public static void Main ( ) { 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 " ) ; } } }