Find the parent node of maximum product Siblings in given Binary Tree
Last Updated :
23 Jul, 2025
Given a binary tree, the task is to find the node whose children have maximum Sibling product in the given Binary Tree. If there are multiple such nodes, return the node which has the maximum value.
Examples:
Input: Tree:
4
/ \
5 2
/ \
3 1
/ \
6 12
Output: 3
Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 12 which are the children of node 3.
Input: Tree:
1
/ \
3 5
/ \ / \
6 9 4 8
Output: 3
Explanation: For the above tree, the maximum product for the siblings is formed for nodes 6 and 9 which are the children of node 3.
Approach using Level Order Traversal:
To solve this problem, level order traversal of the Binary Tree can be used to find the maximum sum of siblings. Follow the following steps:
- Start level order traversal of the tree from root of the tree.
- For each node, check if it has both the child.
- If yes, then find the node with maximum product of children and store this node value in a reference variable.
- Update the node value in reference variable if any node is found with greater product of children.
- If the current node don't have both children, then skip that node
- Return the node value in reference variable, as it contains the node with maximum product of children, or the parent of maximum product siblings.
Below is the implementation of the above approach:
C++
// C++ code to find the Parent Node
// of maximum product Siblings
// in given Binary Tree
#include <bits/stdc++.h>
using namespace std;
// Structure for Node
struct Node {
int data;
Node *left, *right;
};
// Function to get a new node
Node* getNode(int data)
{
// Allocate space
Node* newNode
= (Node*)malloc(sizeof(Node));
// Put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to get the parent
// of siblings with maximum product
int maxproduct(Node* root)
{
int mproduct = INT_MIN;
int ans = 0;
// Checking base case
if (root == NULL
|| (root->left == NULL
&& root->right == NULL))
return 0;
// Declaration of queue to run
// level order traversal
queue<Node*> q;
q.push(root);
// Loop to implement level order traversal
while (!q.empty()) {
Node* temp = q.front();
q.pop();
// If both the siblings are present
// then take their product
if (temp->right && temp->left) {
int curr_max
= temp->right->data
* temp->left->data;
if (mproduct < curr_max) {
mproduct = curr_max;
ans = temp->data;
}
else if (mproduct == curr_max) {
// if max product is equal to
// curr_max then consider node
// which has maximum value
ans = max(ans, temp->data);
}
}
// pushing childs in the queue
if (temp->right) {
q.push(temp->right);
}
if (temp->left) {
q.push(temp->left);
}
}
return ans;
}
// Driver Code
int main()
{
/* Binary tree creation
1
/ \
3 5
/ \ / \
6 9 4 8
*/
Node* root = getNode(1);
root->left = getNode(3);
root->right = getNode(5);
root->left->left = getNode(6);
root->left->right = getNode(9);
root->right->left = getNode(4);
root->right->right = getNode(8);
cout << maxproduct(root) << endl;
return 0;
}
Java
// Java code to find the Parent Node
// of maximum product Siblings
// in given Binary Tree
import java.util.LinkedList;
import java.util.Queue;
class GFG {
// Structure for Node
static class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to get a new node
public static Node getNode(int data) {
// Allocate space
Node newNode = new Node(data);
// Put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// Function to get the parent
// of siblings with maximum product
public static int maxproduct(Node root) {
int mproduct = Integer.MIN_VALUE;
int ans = 0;
// Checking base case
if (root == null
|| (root.left == null
&& root.right == null))
return 0;
// Declaration of queue to run
// level order traversal
Queue<Node> q = new LinkedList<Node>();
q.add(root);
// Loop to implement level order traversal
while (!q.isEmpty()) {
Node temp = q.peek();
q.remove();
// If both the siblings are present
// then take their product
if (temp.right != null && temp.left != null) {
int curr_max = temp.right.data
* temp.left.data;
if (mproduct < curr_max) {
mproduct = curr_max;
ans = temp.data;
} else if (mproduct == curr_max) {
// if max product is equal to
// curr_max then consider node
// which has maximum value
ans = Math.max(ans, temp.data);
}
}
// pushing childs in the queue
if (temp.right != null) {
q.add(temp.right);
}
if (temp.left != null) {
q.add(temp.left);
}
}
return ans;
}
// Driver Code
public static void main(String args[]) {
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
Node root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
System.out.println(maxproduct(root));
}
}
// This code is contributed by gfgking.
Python3
# Python Program to implement
# the above approach
# Structure of a node of binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get a new node
def getNode(data):
# Allocate space
newNode = Node(data)
return newNode
# Function to get the parent
# of siblings with maximum product
def maxproduct(root):
mproduct = 10 ** -9
ans = 0;
# Checking base case
if (root == None or (root.left == None and root.right == None)):
return 0;
# Declaration of queue to run
# level order traversal
q = [];
q.append(root);
# Loop to implement level order traversal
while (len(q)):
temp = q[0];
q.pop(0);
# If both the siblings are present
# then take their product
if (temp.right and temp.left):
curr_max = temp.right.data * temp.left.data;
if (mproduct < curr_max):
mproduct = curr_max
ans = temp.data
elif (mproduct == curr_max):
# if max product is equal to
# curr_max then consider node
# which has maximum value
ans = max(ans, temp.data)
# pushing childs in the queue
if (temp.right):
q.append(temp.right)
if (temp.left):
q.append(temp.left)
return ans
# Driver Code
""" Binary tree creation
1
/ \
3 5
/ \ / \
6 9 4 8
"""
root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
print(maxproduct(root));
# This code is contributed by gfgking
C#
// C# code to find the Parent Node
// of maximum product Siblings
// in given Binary Tree
using System;
using System.Collections.Generic;
public class GFG {
// Structure for Node
class Node {
public int data;
public Node left;
public Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to get a new node
static Node getNode(int data) {
// Allocate space
Node newNode = new Node(data);
// Put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// Function to get the parent
// of siblings with maximum product
static int maxproduct(Node root) {
int mproduct = int.MinValue;
int ans = 0;
// Checking base case
if (root == null
|| (root.left == null
&& root.right == null))
return 0;
// Declaration of queue to run
// level order traversal
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
// Loop to implement level order traversal
while (q.Count!=0) {
Node temp = q.Peek();
q.Dequeue();
// If both the siblings are present
// then take their product
if (temp.right != null && temp.left != null) {
int curr_max = temp.right.data
* temp.left.data;
if (mproduct < curr_max) {
mproduct = curr_max;
ans = temp.data;
} else if (mproduct == curr_max) {
// if max product is equal to
// curr_max then consider node
// which has maximum value
ans = Math.Max(ans, temp.data);
}
}
// pushing childs in the queue
if (temp.right != null) {
q.Enqueue(temp.right);
}
if (temp.left != null) {
q.Enqueue(temp.left);
}
}
return ans;
}
// Driver Code
public static void Main(String []args) {
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
Node root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
Console.WriteLine(maxproduct(root));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Structure of a node of binary tree
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to get a new node
function getNode(data)
{
// Allocate space
let newNode
= new Node(data);
return newNode;
}
// Function to get the parent
// of siblings with maximum product
function maxproduct(root) {
let mproduct = Number.MIN_VALUE;
let ans = 0;
// Checking base case
if (root == null
|| (root.left == null
&& root.right == null))
return 0;
// Declaration of queue to run
// level order traversal
let q = [];
q.push(root);
// Loop to implement level order traversal
while (!q.length == 0) {
let temp = q[0];
q.shift();
// If both the siblings are present
// then take their product
if (temp.right && temp.left) {
let curr_max
= temp.right.data
* temp.left.data;
if (mproduct < curr_max) {
mproduct = curr_max;
ans = temp.data;
}
else if (mproduct == curr_max) {
// if max product is equal to
// curr_max then consider node
// which has maximum value
ans = Math.max(ans, temp.data);
}
}
// pushing childs in the queue
if (temp.right) {
q.push(temp.right);
}
if (temp.left) {
q.push(temp.left);
}
}
return ans;
}
// Driver Code
/* Binary tree creation
1
/ \
3 5
/ \ / \
6 9 4 8
*/
let root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
document.write(maxproduct(root) + "<br>");
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(V) where V is the number of nodes in the tree.
Auxiliary Space: O(V).
- The idea is to traverse the tree in postorder fashion .
- Recursively , call the left subtree.
- Recursively , call the right subtree.
- Get , the product of left child and right child and update the max variable and max parent variable with parent root of left and right child.
- Here , max parent variable will be storing the parent node of the maximum product siblings.
Below is the Implementation of this Approach :-
C++
#include <climits>
#include <iostream>
// Structure for Node
struct Node {
int data;
Node* left;
Node* right;
Node(int data)
: data(data)
, left(nullptr)
, right(nullptr)
{
}
};
// Function to get a new node
Node* getNode(int data)
{
// Allocate space
Node* newNode = new Node(data);
// Put in the data
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}
// Initialize, parentNode with -1
int parentNode = -1;
// Initialize, maxProductVal with INT_MIN
int maxProductVal = INT_MIN;
// Forward declaration of the helper function
int helper(Node* root);
// Function to get the parent of siblings with maximum
// product
int calculateMaxProduct(Node* root)
{
// calling helper function to get ParentNode
helper(root);
return parentNode;
}
int helper(Node* root)
{
// Base Case
if (root == nullptr) {
return 0;
}
// recursively, calling left part
int left = helper(root->left);
// recursively, calling right part
int right = helper(root->right);
// multiplying left and right to get product of the root
int currProduct = left * right;
// update maxProduct
if (maxProductVal < currProduct) {
maxProductVal = currProduct;
// update the parentNode
parentNode = root->data;
}
// return root data for every node
return root->data;
}
// Driver Code
int main()
{
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
Node* root = getNode(1);
root->left = getNode(3);
root->right = getNode(5);
root->left->left = getNode(6);
root->left->right = getNode(9);
root->right->left = getNode(4);
root->right->right = getNode(8);
std::cout << calculateMaxProduct(root) << std::endl;
// Free allocated memory
delete root->left->left;
delete root->left->right;
delete root->right->left;
delete root->right->right;
delete root->left;
delete root->right;
delete root;
return 0;
}
Java
// Java code to find the Parent Node
// of maximum product Siblings
// in given Binary Tree
import java.util.LinkedList;
import java.util.Queue;
class GFG {
// Structure for Node
static class Node {
int data;
Node left;
Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to get a new node
public static Node getNode(int data)
{
// Allocate space
Node newNode = new Node(data);
// Put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// Initialize , parentNode with -1
static int parentNode = -1;
// Initialize , maxProduct with INT_MIN
static int maxProduct = Integer.MIN_VALUE;
// Function to get the parent
// of siblings with maximum product
public static int maxproduct(Node root)
{
// calling helper function to get
// ParentNode
helper(root);
return parentNode;
}
static int helper(Node root)
{
// Base Case
if (root == null) {
return 0;
}
// recursively , calling left part
int left = helper(root.left);
// recursively , calling right part
int right = helper(root.right);
// multiplying left and right to get product
// of the root
int currProduct = left * right;
// update maxProduct
if (maxProduct < currProduct) {
maxProduct = currProduct;
// update the parentNode
parentNode = root.data;
}
// return root data for every node
return root.data;
}
// Driver Code
public static void main(String args[])
{
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
Node root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
System.out.println(maxproduct(root));
}
}
// This code is contributed by srimann7
Python
import sys
# Class definition for Node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get a new node
def get_node(data):
# Allocate space
new_node = Node(data)
# Put in the data
new_node.data = data
new_node.left = new_node.right = None
return new_node
# Initialize parentNode with -1
parent_node = -1
# Initialize max_product_val with INT_MIN
max_product_val = -sys.maxsize - 1
# Helper function to calculate the maximum product
def helper(root):
global parent_node, max_product_val
# Base Case
if root is None:
return 0
# Recursively calling left part
left = helper(root.left)
# Recursively calling right part
right = helper(root.right)
# Multiplying left and right to get the product of the root
curr_product = left * right
# Update max_product_val
if max_product_val < curr_product:
max_product_val = curr_product
# Update the parent_node
parent_node = root.data
# Return root data for every node
return root.data
# Function to calculate the parent of siblings with the maximum product
def calculate_max_product(root):
# Calling the helper function to get parent_node
helper(root)
return parent_node
# Driver Code
if __name__ == "__main__":
"""
Binary tree creation
1
/ \
3 5
/ \ / \
6 9 4 8
"""
root = get_node(1)
root.left = get_node(3)
root.right = get_node(5)
root.left.left = get_node(6)
root.left.right = get_node(9)
root.right.left = get_node(4)
root.right.right = get_node(8)
print(calculate_max_product(root))
# Free allocated memory
del root.left.left
del root.left.right
del root.right.left
del root.right.right
del root.left
del root.right
del root
C#
using System;
// Structure for Node
public class Node {
public int data;
public Node left;
public Node right;
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree {
// Initialize parentNode with -1
private static int parentNode = -1;
// Initialize maxProductVal with int.MinValue
private static int maxProductVal = int.MinValue;
// Function to get the parent of siblings with maximum
// product
private static int CalculateMaxProduct(Node root)
{
// calling helper function to get parentNode
Helper(root);
return parentNode;
}
private static int Helper(Node root)
{
// Base Case
if (root == null) {
return 0;
}
// Recursively calling the left part
int left = Helper(root.left);
// Recursively calling the right part
int right = Helper(root.right);
// Multiplying left and right to get the product of
// the root
int currProduct = left * right;
// Update maxProduct
if (maxProductVal < currProduct) {
maxProductVal = currProduct;
// Update the parentNode
parentNode = root.data;
}
// Return root data for every node
return root.data;
}
// Driver Code
public static void Main()
{
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
Node root = new Node(1);
root.left = new Node(3);
root.right = new Node(5);
root.left.left = new Node(6);
root.left.right = new Node(9);
root.right.left = new Node(4);
root.right.right = new Node(8);
Console.WriteLine(CalculateMaxProduct(root));
// No need to free memory in C#, as it is managed by
// the garbage collector
}
}
JavaScript
// Structure for Node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to get a new node
function getNode(data) {
const newNode = new Node(data);
newNode.data = data;
newNode.left = null;
newNode.right = null;
return newNode;
}
// Initialize parentNode with -1
let parentNode = -1;
// Initialize maxProductVal with Number.MIN_SAFE_INTEGER
let maxProductVal = Number.MIN_SAFE_INTEGER;
// Forward declaration of the helper function
function helper(root) {
// Base Case
if (root === null) {
return 0;
}
// Recursively calling left part
const left = helper(root.left);
// Recursively calling right part
const right = helper(root.right);
// Multiplying left and right to get product of the root
const currProduct = left * right;
// Update maxProduct
if (maxProductVal < currProduct) {
maxProductVal = currProduct;
// Update the parentNode
parentNode = root.data;
}
// Return root data for every node
return root.data;
}
// Function to get the parent of siblings with maximum product
function calculateMaxProduct(root) {
// Calling helper function to get parentNode
helper(root);
return parentNode;
}
// Driver Code
/*
* Binary tree creation
* 1
* / \
* 3 5
* / \ / \
* 6 9 4 8
*/
const root = getNode(1);
root.left = getNode(3);
root.right = getNode(5);
root.left.left = getNode(6);
root.left.right = getNode(9);
root.right.left = getNode(4);
root.right.right = getNode(8);
console.log(calculateMaxProduct(root));
Time Complexity: O(N) , where N is the number of nodes in the tree
Auxiliary Space : O(N) , recursion stack space
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