VOOZH about

URL: https://www.geeksforgeeks.org/dsa/gcd-from-root-to-leaf-path-in-an-n-ary-tree/

⇱ GCD from root to leaf path in an N-ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

GCD from root to leaf path in an N-ary tree

Last Updated : 11 Jul, 2025

Given an N-ary tree and an array val[] which stores the values associated with all the nodes. Also given are a leaf node X and N integers which denotes the value of the node. The task is to find the gcd of all the numbers in the node in the path between leaf to the root. 
Examples: 
 

Input: 
 1
 / \ 
 2 3
 / / \ 
 4 5 6 
 / \
 7 8 

val[] = { -1, 6, 2, 6, 3, 4, 12, 10, 18 } 
leaf = 8 
Output: 6 

GCD(val[1], val[3], val[6], val[8]) = GCD(6, 6, 12, 18) = 6 

Input:
 1
 / \ 
 2 3
 / / \ 
 4 5 6 
 / \
 7 8 

val[] = { 6, 2, 6, 3, 4, 12, 10, 18 }
leaf = 5 
Output: 2


 


Approach: The problem can be solved using DFS in a tree. In the DFS function, we include an extra parameter G with the initial value as the root. Every time we visit a new node by calling DFS function recursively, we update the value of G to gcd(G, val[node]) . Once we reach the given leaf node, we print the value of gcd(G, val[leaf-node]) and break out of DFS function. 
Below is the implementation of the above approach: 
 


Output: 
2

 

Time Complexity: O(NlogN), as we are traversing the graph using DFS (recursion). Where N is the number of nodes in the graph.

Auxiliary Space: O(N), as we are using extra space for the recursive stack. Where N is the number of nodes in the graph.

Comment
Article Tags: