![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
3
Time Complexity: O(N2)
Auxiliary Space: O(N)