Find maximum GCD value from root to leaf in a Binary tree | Java program for the above approach ; Initialise to update the maximum gcd value from all the path ; Node structure ; Left & right child of the node ; Initialize constructor ; Function to find gcd of a and b ; Function to find the gcd of a path ; Function to find the maximum value of gcd from root to leaf in a Binary tree ; Check if root is not null ; Find the maximum gcd of path value and store in global maxm variable ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code ; Given Tree ; Function call ; Print the maximum AND value
import java . util . * ; class GFG { static int maxm = 0 ; static class Node { int val ; Node left , right ; Node ( int x ) { val = x ; left = null ; right = null ; } } ; static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int find_gcd ( Vector < Integer > arr ) { if ( arr . size ( ) == 1 ) return arr . get ( 0 ) ; int g = arr . get ( 0 ) ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { g = gcd ( g , arr . get ( 1 ) ) ; } return g ; } static void maxm_gcd ( Node root , Vector < Integer > ans ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { ans . add ( root . val ) ; maxm = Math . max ( find_gcd ( ans ) , maxm ) ; return ; } ans . add ( root . val ) ; maxm_gcd ( root . left , ans ) ; maxm_gcd ( root . right , ans ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 15 ) ; root . left = new Node ( 3 ) ; root . right = new Node ( 7 ) ; root . left . left = new Node ( 15 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 31 ) ; root . right . right = new Node ( 9 ) ; maxm_gcd ( root , new Vector < > ( ) ) ; System . out . print ( maxm + "NEW_LINE"); } }