Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K | Java program to implement the above approach ; Initialize the adjacency list and visited array ; Function to find the number of root to leaf paths that contain atmost m consecutive nodes with value k ; Mark the current node as visited ; If value at current node is k ; Increment counter ; If count is greater than m return from that path ; Path is allowed if size of present node becomes 0 i . e it has no child root and no more than m consecutive 1 's ; Driver Code ; Desigining the tree ; Counter counts no . of consecutive nodes
import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] adj = new Vector [ 100005 ] ; static int [ ] visited = new int [ 100005 ] ; static int ans = 0 ; static void dfs ( int node , int count , int m , int arr [ ] , int k ) { visited [ node ] = 1 ; if ( arr [ node - 1 ] == k ) { count ++ ; } else { count = 0 ; } if ( count > m ) { return ; } if ( adj [ node ] . size ( ) == 1 && node != 1 ) { ans ++ ; } for ( int x : adj [ node ] ) { if ( visited [ x ] == 0 ) { dfs ( x , count , m , arr , k ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 3 , 2 , 1 , 2 , 1 } ; int N = 7 , K = 2 , M = 2 ; for ( int i = 0 ; i < adj . length ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; adj [ 1 ] . add ( 2 ) ; adj [ 2 ] . add ( 1 ) ; adj [ 1 ] . add ( 3 ) ; adj [ 3 ] . add ( 1 ) ; adj [ 2 ] . add ( 4 ) ; adj [ 4 ] . add ( 2 ) ; adj [ 2 ] . add ( 5 ) ; adj [ 5 ] . add ( 2 ) ; adj [ 3 ] . add ( 6 ) ; adj [ 6 ] . add ( 3 ) ; adj [ 3 ] . add ( 7 ) ; adj [ 7 ] . add ( 3 ) ; int counter = 0 ; dfs ( 1 , counter , M , arr , K ) ; System . out . print ( ans + "NEW_LINE"); } }