Find maximum GCD value from root to leaf in a Binary tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxm = 0 ; struct Node { int val ; Node * left , * right ; Node ( int x ) { val = x ; left = NULL ; right = NULL ; } } ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } int find_gcd ( vector < int > arr ) { if ( arr . size ( ) == 1 ) return arr [ 0 ] ; int g = arr [ 0 ] ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { g = gcd ( g , arr [ i ] ) ; } return g ; } void maxm_gcd ( Node * root , vector < int > ans ) { if ( ! root ) return ; if ( root -> left == NULL and root -> right == NULL ) { ans . push_back ( root -> val ) ; maxm = max ( find_gcd ( ans ) , maxm ) ; return ; } ans . push_back ( root -> val ) ; maxm_gcd ( root -> left , ans ) ; maxm_gcd ( root -> right , ans ) ; } int main ( ) { 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 , { } ) ; cout << maxm << endl ; return 0 ; }