Find the maximum GCD of the siblings of a Binary Tree
Last Updated :
12 Jul, 2025
Given a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it.
Example:
Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}}
Output: 6
Explanation:

For the above tree, the maximum GCD for the siblings is formed for the nodes 6 and 12 for the children of node 3.
Input: arr[][] = {{5, 4}, {5, 8}, {4, 6}, {4, 9}, {8, 10}, {10, 20}, {10, 30}}
Output: 10
Approach: The idea is to form a vector and store the tree in the form of the vector. After storing the tree in the form of a vector, the following cases occur:
- If the vector size is 0 or 1, then print 0 as GCD could not be found.
- For all other cases, since we store the tree in the form of a pair, we consider the first values of two pairs and compare them. But first, you need to Sort the pair of edges.
For example, let's assume there are two pairs in the vector A and B. We check if:
A.first == B.first
- If both of them match, then both of them belongs to the same parent. Therefore, we compute the GCD of the second values in the pairs and finally print the maximum of all such GCD's.
Below is the implementation of the above approach:
C++
// C++ program to find the maximum
// GCD of the siblings of a binary tree
#include <bits/stdc++.h>
using namespace std;
// Function to find maximum GCD
int max_gcd(vector<pair<int, int> >& v)
{
// No child or Single child
if (v.size() == 1 || v.size() == 0)
return 0;
sort(v.begin(), v.end());
// To get the first pair
pair<int, int> a = v[0];
pair<int, int> b;
int ans = INT_MIN;
for (int i = 1; i < v.size(); i++) {
b = v[i];
// If both the pairs belongs to
// the same parent
if (b.first == a.first)
// Update ans with the max
// of current gcd and
// gcd of both children
ans
= max(ans,
__gcd(a.second,
b.second));
// Update previous
// for next iteration
a = b;
}
return ans;
}
// Driver function
int main()
{
vector<pair<int, int> > v;
v.push_back(make_pair(5, 4));
v.push_back(make_pair(5, 8));
v.push_back(make_pair(4, 6));
v.push_back(make_pair(4, 9));
v.push_back(make_pair(8, 10));
v.push_back(make_pair(10, 20));
v.push_back(make_pair(10, 30));
cout << max_gcd(v);
return 0;
}
Java
// Java program to find the maximum
// GCD of the siblings of a binary tree
import java.util.*;
import java.lang.*;
class GFG{
// Function to find maximum GCD
static int max_gcd(ArrayList<int[]> v)
{
// No child or Single child
if (v.size() == 1 || v.size() == 0)
return 0;
Collections.sort(v, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0]-b[0];
}
});
// To get the first pair
int[] a = v.get(0);
int[] b = new int[2];
int ans = Integer.MIN_VALUE;
for(int i = 1; i < v.size(); i++)
{
b = v.get(i);
// If both the pairs belongs to
// the same parent
if (b[0] == a[0])
// Update ans with the max
// of current gcd and
// gcd of both children
ans = Math.max(ans,
gcd(a[1],
b[1]));
// Update previous
// for next iteration
a = b;
}
return ans;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Driver code
public static void main(String[] args)
{
ArrayList<int[]> v = new ArrayList<>();
v.add(new int[]{5, 4});
v.add(new int[]{5, 8});
v.add(new int[]{4, 6});
v.add(new int[]{4, 9});
v.add(new int[]{8, 10});
v.add(new int[]{10, 20});
v.add(new int[]{10, 30});
System.out.println(max_gcd(v));
}
}
// This code is contributed by offbeat
Python
# Python3 program to find the maximum
# GCD of the siblings of a binary tree
from math import gcd
# Function to find maximum GCD
def max_gcd(v):
# No child or Single child
if (len(v) == 1 or len(v) == 0):
return 0
v.sort()
# To get the first pair
a = v[0]
ans = -10**9
for i in range(1, len(v)):
b = v[i]
# If both the pairs belongs to
# the same parent
if (b[0] == a[0]):
# Update ans with the max
# of current gcd and
# gcd of both children
ans = max(ans, gcd(a[1], b[1]))
# Update previous
# for next iteration
a = b
return ans
# Driver function
if __name__ == '__main__':
v=[]
v.append([5, 4])
v.append([5, 8])
v.append([4, 6])
v.append([4, 9])
v.append([8, 10])
v.append([10, 20])
v.append([10, 30])
print(max_gcd(v))
# This code is contributed by mohit kumar 29
C#
// C# program to find the maximum
// GCD of the siblings of a binary tree
using System.Collections;
using System;
class GFG{
// Function to find maximum GCD
static int max_gcd(ArrayList v)
{
// No child or Single child
if (v.Count == 1 || v.Count == 0)
return 0;
v.Sort();
// To get the first pair
int[] a = (int [])v[0];
int[] b = new int[2];
int ans = -10000000;
for(int i = 1; i < v.Count; i++)
{
b = (int[])v[i];
// If both the pairs belongs to
// the same parent
if (b[0] == a[0])
// Update ans with the max
// of current gcd and
// gcd of both children
ans = Math.Max(ans, gcd(a[1], b[1]));
// Update previous
// for next iteration
a = b;
}
return ans;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Driver code
public static void Main(string[] args)
{
ArrayList v = new ArrayList();
v.Add(new int[]{5, 4});
v.Add(new int[]{5, 8});
v.Add(new int[]{4, 6});
v.Add(new int[]{4, 9});
v.Add(new int[]{8, 10});
v.Add(new int[]{10, 20});
v.Add(new int[]{10, 30});
Console.Write(max_gcd(v));
}
}
// This code is contributed by rutvik_56
JavaScript
// JavaScript program to find the maximum
// GCD of the siblings of a binary tree
// Function to find maximum GCD
function max_gcd(v)
{
// No child or Single child
if (v.length == 1 || v.length == 0)
return 0;
v.sort((a, b) => a - b);
// To get the first pair
let a = v[0];
let b;
let ans = Number.MIN_SAFE_INTEGER;
for (let i = 1; i < v.length; i++) {
b = v[i];
// If both the pairs belongs to
// the same parent
if (b[0] == a[0])
// Update ans with the max
// of current gcd and
// gcd of both children
ans
= Math.max(ans, gcd(a[1], b[1]));
// Update previous
// for next iteration
a = b;
}
return ans;
}
function gcd(a, b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Driver function
let v = new Array();
v.push([5, 4]);
v.push([5, 8]);
v.push([4, 6]);
v.push([4, 9]);
v.push([8, 10]);
v.push([10, 20]);
v.push([10, 30]);
console.log(max_gcd(v));
// This code is contributed by gfgking
Time Complexity: O(nlogn), as sort() takes O(nlogn) time.
Auxiliary Space: O(1)
Another Approach:
The approach is to traverse the binary tree in a postorder manner and for each node, compute the greatest common divisor (GCD) of the values of its left and right children. If both children exist and their GCD is greater than the current maximum GCD, update the maximum GCD. Then return the GCD of the current node value and the maximum of its children's GCDs.
Here is an implementation of above approach:
C++
// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
// Structure of Tree Node
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x)
: val(x)
, left(NULL)
, right(NULL)
{
}
};
// Find out gcd
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int max_gcd_helper(TreeNode* root, int& ans)
{
if (!root)
return 0;
int left_gcd = max_gcd_helper(root->left, ans);
int right_gcd = max_gcd_helper(root->right, ans);
if (left_gcd != 0 && right_gcd != 0) {
int siblings_gcd = gcd(left_gcd, right_gcd);
ans = max(ans, siblings_gcd);
}
return (root->left) ? gcd(root->val, left_gcd)
: root->val;
}
int max_gcd(TreeNode* root)
{
int ans = 0;
max_gcd_helper(root, ans);
return ans;
}
// Driver code
int main()
{
TreeNode* root = new TreeNode(10);
root->left = new TreeNode(5);
root->right = new TreeNode(15);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(8);
root->right->left = new TreeNode(10);
root->right->right = new TreeNode(20);
// Function call
cout << max_gcd(root); // Output: 10
return 0;
}
Java
import java.io.*;
import java.util.Objects;
// Definition of TreeNode
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) {
val = x;
left = null;
right = null;
}
}
public class GFG {
// Find out gcd
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Helper function to find the
// maximum GCD in the tree
private static int maxGCDHelper(TreeNode root, int[] ans) {
if (root == null)
return 0;
int leftGCD = maxGCDHelper(root.left, ans);
int rightGCD = maxGCDHelper(root.right, ans);
if (leftGCD != 0 && rightGCD != 0) {
int siblingsGCD = gcd(leftGCD, rightGCD);
ans[0] = Math.max(ans[0], siblingsGCD);
}
return (root.left != null) ? gcd(root.val, leftGCD) : root.val;
}
// Function to find the maximum GCD in the tree
public static int maxGCD(TreeNode root) {
int[] ans = { 0 };
// Store the result in an array to
// pass by reference
maxGCDHelper(root, ans);
return ans[0];
}
// Driver code
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(20);
// Function call
System.out.println(maxGCD(root));
}
}
Python
# Python3 Implementation
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def max_gcd_helper(root, ans):
if not root:
return 0
left_gcd = max_gcd_helper(root.left, ans)
right_gcd = max_gcd_helper(root.right, ans)
if left_gcd != 0 and right_gcd != 0:
siblings_gcd = gcd(left_gcd, right_gcd)
ans[0] = max(ans[0], siblings_gcd)
return root.val if not root.left else gcd(root.val, left_gcd)
def max_gcd(root):
ans = [0]
max_gcd_helper(root, ans)
return ans[0]
# Driver code
if __name__ == "__main__":
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(4)
root.left.right = TreeNode(8)
root.right.left = TreeNode(10)
root.right.right = TreeNode(20)
# Function call
print(max_gcd(root)) # Output: 10
C#
// C# implementation
using System;
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
left = null;
right = null;
}
}
public class Program
{
// Find out gcd
public static int GCD(int a, int b)
{
if (b == 0)
return a;
return GCD(b, a % b);
}
public static int max_gcd_helper(TreeNode root, ref int ans)
{
if (root == null)
return 0;
int leftGCD = max_gcd_helper(root.left, ref ans);
int rightGCD = max_gcd_helper(root.right, ref ans);
if (leftGCD != 0 && rightGCD != 0)
{
int siblingsGCD = GCD(leftGCD, rightGCD);
ans = Math.Max(ans, siblingsGCD);
}
return (root.left != null) ? GCD(root.val, leftGCD) : root.val;
}
public static int MaxGCD(TreeNode root)
{
int ans = 0;
max_gcd_helper(root, ref ans);
return ans;
}
// Driver code
public static void Main(string[] args)
{
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(20);
Console.WriteLine(MaxGCD(root)); // Output: 10
}
}
// Code is Added by Avinash Wani
JavaScript
// Structure of Tree Node
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Find out gcd
function gcd(a, b) {
if (b === 0)
return a;
return gcd(b, a % b);
}
function max_gcd_helper(root, ans) {
if (!root)
return 0;
const left_gcd = max_gcd_helper(root.left, ans);
const right_gcd = max_gcd_helper(root.right, ans);
if (left_gcd !== 0 && right_gcd !== 0) {
const siblings_gcd = gcd(left_gcd, right_gcd);
ans[0] = Math.max(ans[0], siblings_gcd);
}
return (root.left) ? gcd(root.val, left_gcd) : root.val;
}
function max_gcd(root) {
const ans = [0];
max_gcd_helper(root, ans);
return ans[0];
}
// Driver code
function main() {
const root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(8);
root.right.left = new TreeNode(10);
root.right.right = new TreeNode(20);
// Function call
console.log(max_gcd(root)); // Output: 10
}
main();
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem