Find maximum GCD value from root to leaf in a Binary tree

Given a Binary Tree, the task is to find the maximum value of GCD from any path from the root node to the leaf node.
Examples:
Input: Below is the given tree:
Output: 3
Explanation:
Path 1: 15->3->5 = gcd(15, 3, 15) =3
Path 2: 15->3->1 =gcd(15, 3, 1) = 1
Path 3: 15->7->31=gcd(15, 7, 31)= 1
Path 4: 15->7->9 = gcd(15, 7, 9) =1, out of these 3 is the maximum.Input: Below is the given tree:
Output: 1
Approach: The idea is to traverse all the paths from the root node to the leaf node and calculate the GCD of all the nodes that occurred in that path. Below are the steps:
- Perform a preorder traversal on the given Binary Tree.
- Iterate over all the paths and track all path values in an array.
- Whenever encountered a leaf value then find the GCD of all the values in an array.
- Update the GCD to the maximum value.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Initialise to update the maximum// gcd value from all the pathint maxm = 0;Â
// Node structurestruct Node {Â Â Â Â int val;Â
    // Left & right child of the node    Node *left, *right;Â
    // Initialize constructor    Node(int x)    {        val = x;        left = NULL;        right = NULL;    }};Â
// Function to find gcd of a and bint gcd(int a, int b){Â Â Â Â if (b == 0)Â Â Â Â Â Â Â Â return a;Â Â Â Â return gcd(b, a % b);}Â
// function to find the gcd of a pathint 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;}Â
// Function to find the maximum value// of gcd from root to leaf// in a Binary treevoid maxm_gcd(Node* root, vector<int> ans){    // Check if root is not null    if (!root)        return;Â
    if (root->left == NULL        and root->right == NULL) {        ans.push_back(root->val);Â
        // Find the maximum gcd of        // path value and store in        // global maxm variable        maxm = max(find_gcd(ans),                   maxm);Â
        return;    }Â
    // Traverse left of binary tree    ans.push_back(root->val);    maxm_gcd(root->left, ans);Â
    // Traverse right of the binary tree    maxm_gcd(root->right, ans);}Â
// Driver Codeint main(){    // Given Tree    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);Â
    // Function Call    maxm_gcd(root, {});Â
    // Print the maximum AND value    cout << maxm << endl;Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Initialise to update the maximum// gcd value from all the pathstatic int maxm = 0;Â
// Node structurestatic class Node {Â Â Â Â int val;Â
    // Left & right child of the node    Node left, right;Â
    // Initialize constructor    Node(int x)    {        val = x;        left = null;        right = null;    }};Â
// Function to find gcd of a and bstatic int gcd(int a, int b){Â Â Â Â if (b == 0)Â Â Â Â Â Â Â Â return a;Â Â Â Â return gcd(b, a % b);}Â
// Function to find the gcd of a pathstatic 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;}Â
// Function to find the maximum value// of gcd from root to leaf// in a Binary treestatic void maxm_gcd(Node root,                      Vector<Integer> ans){         // Check if root is not null    if (root == null)        return;Â
    if (root.left == null &&         root.right == null)     {        ans.add(root.val);Â
        // Find the maximum gcd of        // path value and store in        // global maxm variable        maxm = Math.max(find_gcd(ans),                        maxm);                                 return;    }Â
    // Traverse left of binary tree    ans.add(root.val);    maxm_gcd(root.left, ans);Â
    // Traverse right of the binary tree    maxm_gcd(root.right, ans);}Â
// Driver Codepublic static void main(String[] args){         // Given Tree    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);Â
    // Function call    maxm_gcd(root, new Vector<>());Â
    // Print the maximum AND value    System.out.print(maxm + "\n");}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of# the above approachÂ
# Initialise to update the maximum# gcd value from all the pathglobal maxmmaxm = 0Â
# Node structureclass Node:Â
    # Initialize constructor    def __init__(self, x):Â
        self.val = x        self.left = None        self.right = NoneÂ
# Function to find gcd of a and bdef gcd(a, b):Â
    if(b == 0):        return a    return gcd(b, a % b)Â
# Function to find the gcd of a pathdef find_gcd(arr):Â
    if(len(arr) == 1):        return arr[0]Â
    g = arr[0]Â
    for i in range(1, len(arr)):        g = gcd(g, arr[i])Â
    return gÂ
# Function to find the maximum value# of gcd from root to leaf# in a Binary treedef maxm_gcd(root, ans):Â
    global maxmÂ
    # Check if root is not null    if(not root):        returnÂ
    if(root.left == None and       root.right == None):        ans.append(root.val)Â
        # Find the maximum gcd of        # path value and store in        # global maxm variable        maxm = max(find_gcd(ans), maxm)Â
        returnÂ
    # Traverse left of binary tree    ans.append(root.val)    maxm_gcd(root.left, ans)Â
    # Traverse right of the binary tree    maxm_gcd(root.right, ans)Â
# Driver Codeif __name__ == '__main__':Â
    # Given Tree    root = Node(15)    root.left = Node(3)    root.right = Node(7)    root.left.left = Node(15)    root.left.right = Node(1)    root.right.left = Node(31)    root.right.right = Node(9)Â
    # Function call    maxm_gcd(root, [])         # Print the maximum AND value    print(maxm)Â
# This code is contributed by Shivam Singh |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{Â
// Initialise to update the maximum// gcd value from all the pathstatic int maxm = 0;Â
// Node structureclass Node {Â Â Â Â public int val;Â
    // Left & right child of the node    public Node left, right;Â
    // Initialize constructor    public Node(int x)    {        val = x;        left = null;        right = null;    }};Â
// Function to find gcd of a and bstatic int gcd(int a, int b){Â Â Â Â if (b == 0)Â Â Â Â Â Â Â Â return a;Â Â Â Â return gcd(b, a % b);}Â
// Function to find the gcd of a pathstatic int find_gcd(List<int> arr){Â Â Â Â if (arr.Count == 1)Â Â Â Â Â Â Â Â return arr[0];Â
    int g = arr[0];Â
    for(int i = 1; i < arr.Count; i++)    {        g = gcd(g, arr[1]);    }    return g;}Â
// Function to find the maximum value// of gcd from root to leaf// in a Binary treestatic void maxm_gcd(Node root,                      List<int> ans){         // Check if root is not null    if (root == null)        return;Â
    if (root.left == null &&         root.right == null)     {        ans.Add(root.val);Â
        // Find the maximum gcd of        // path value and store in        // global maxm variable        maxm = Math.Max(find_gcd(ans),                                 maxm);                                 return;    }Â
    // Traverse left of binary tree    ans.Add(root.val);    maxm_gcd(root.left, ans);Â
    // Traverse right of the binary tree    maxm_gcd(root.right, ans);}Â
// Driver Codepublic static void Main(String[] args){         // Given Tree    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);Â
    // Function call    maxm_gcd(root, new List<int>());Â
    // Print the maximum AND value    Console.Write(maxm + "\n");}}Â
// This code is contributed by sapnasingh4991 |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Initialise to update the maximum// gcd value from all the pathlet maxm = 0;Â
// Node structureclass Node {Â
    // Initialize constructor    constructor(x)    {        this.val = x;        this.left = null;        this.right = null;    }}Â
var root;Â
// Function to find gcd of a and bfunction gcd(a, b){Â Â Â Â if (b == 0)Â Â Â Â Â Â Â Â return a;Â Â Â Â Â Â Â Â Â Â Â Â Â return gcd(b, a % b);}Â
// Function to find the gcd of a pathfunction 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 to find the maximum value// of gcd from root to leaf// in a Binary treefunction maxm_gcd(root, ans){         // Check if root is not null    if (root == null)        return;Â
    if (root.left == null &&         root.right == null)     {        ans.push(root.val);Â
        // Find the maximum gcd of        // path value and store in        // global maxm variable        maxm = Math.max(find_gcd(ans),                        maxm);                                 return;    }Â
    // Traverse left of binary tree    ans.push(root.val);    maxm_gcd(root.left, ans);Â
    // Traverse right of the binary tree    maxm_gcd(root.right, ans);}Â
// Driver CodeÂ
// Given Treeroot = 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);Â
// Function calllet arr = [];maxm_gcd(root, arr);Â
// Print the maximum AND valuedocument.write(maxm);Â
// This code is contributed by Dharanendra L V.Â
</script> |
Output:Â
3
Â
Time Complexity: O(N2)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




