Find maximum GCD value from root to leaf in a Binary tree | Initialise to update the maximum gcd value from all the path ; Node structure ; 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 ; Given Tree ; Function call ; Print the maximum AND value
let maxm = 0 ; class Node { constructor ( x ) { this . val = x ; this . left = null ; this . right = null ; } } var root ; function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function find_gcd ( arr ) { if ( arr . length == 1 ) return arr [ 0 ] ; let g = arr [ 0 ] ; for ( let i = 1 ; i < arr . length ; i ++ ) { g = gcd ( g , arr [ 1 ] ) ; } return g ; } function maxm_gcd ( root , ans ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { ans . push ( root . val ) ; maxm = Math . max ( find_gcd ( ans ) , maxm ) ; return ; } ans . push ( root . val ) ; maxm_gcd ( root . left , ans ) ; maxm_gcd ( root . right , ans ) ; } 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 ) ; let arr = [ ] ; maxm_gcd ( root , arr ) ; document . write ( maxm ) ;