text: Print all paths of the Binary Tree with maximum element in each path greater than or equal to K | Java program to print paths with maximum element in the path greater than K ; A Binary Tree node ; A utility function to create a new node ; A recursive function to print the paths whose maximum element is greater than or equal to K . ; If the current node value is greater than or equal to k , then all the subtrees following that node will get printed , flag = 1 indicates to print the required path ; If the leaf node is encountered , then the path is printed if the size of the path vector is greater than 0 ; Append the node to the path vector ; Recur left and right subtrees ; Backtracking to return the vector and print the path if the flag is 1 ; Function to initialize the variables and call the utility function to print the paths with maximum values greater than or equal to K ; Initialize flag ; ans is used to check empty condition ; Call function that print path ; If the path doesn 't exist ; Driver code ; Constructing the following tree : 10 / \ 5 8 / \ / \ 29 2 1 98 / \ 20 50
code: import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static int ans ; static Node newNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return ( newNode ) ; } static void findPathUtil ( Node root , int k , Vector < Integer > path , int flag ) { if ( root == null ) return ; if ( root . data >= k ) flag = 1 ; if ( root . left == null && root . right == null ) { if ( flag == 1 ) { ans = 1 ; System . out . print ( " ( " ) ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { System . out . print ( path . get ( i ) + " , ▁ " ) ; } System . out . print ( root . data + " ) , ▁ " ) ; } return ; } path . add ( root . data ) ; findPathUtil ( root . left , k , path , flag ) ; findPathUtil ( root . right , k , path , flag ) ; path . remove ( path . size ( ) - 1 ) ; } static void findPath ( Node root , int k ) { int flag = 0 ; ans = 0 ; Vector < Integer > v = new Vector < Integer > ( ) ; findPathUtil ( root , k , v , flag ) ; if ( ans == 0 ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int K = 25 ; Node root = newNode ( 10 ) ; root . left = newNode ( 5 ) ; root . right = newNode ( 8 ) ; root . left . left = newNode ( 29 ) ; root . left . right = newNode ( 2 ) ; root . right . right = newNode ( 98 ) ; root . right . left = newNode ( 1 ) ; root . right . right . right = newNode ( 50 ) ; root . left . left . left = newNode ( 20 ) ; findPath ( root , K ) ; } }