VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-gcd-value-from-root-to-leaf-in-a-binary-tree/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

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:

👁 Image

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:

👁 Image

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:

  1. Perform a preorder traversal on the given Binary Tree.
  2. Iterate over all the paths and track all path values in an array.
  3. Whenever encountered a leaf value then find the GCD of all the values in an array.
  4. Update the GCD to the maximum value.

Below is the implementation of the above approach:


Output: 
3

 

Time Complexity: O(N2)
Auxiliary Space: O(N)

Comment