Sum and Product of maximum and minimum element in Binary Tree
Last Updated :
23 Feb, 2023
Given a Binary Tree. The task is to find the sum and product of the maximum and minimum elements in it.
For example, sum of the maximum and minimum elements in the following binary tree is 10 and the product is 9.

The idea is to traverse the tree and find the maximum and minimum elements in the tree and print their product and sum.
To find the maximum element in the Binary Tree, recursively traverse the tree and return the maximum of three below:
- Current Node’s data.
- Maximum in node’s left subtree.
- Maximum in node’s right subtree.
Similarly, we can find the minimum element in the binary tree by comparing three values.
Implementation:
C++
// CPP program to find sum and product of
// maximum and minimum in a Binary Tree
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
// A tree node
class Node
{
public:
int data;
Node *left, *right;
/* Constructor that allocates
a new node with the given data
and NULL left and right pointers. */
Node(int data)
{
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
// Function to return minimum value
// in a given Binary Tree
int findMin(Node* root)
{
// Base case
if (root == NULL)
return INT_MAX;
// Return minimum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMin(root->left);
int rres = findMin(root->right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
// Function to returns maximum value
// in a given Binary Tree
int findMax(Node* root)
{
// Base case
if (root == NULL)
return INT_MIN;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMax(root->left);
int rres = findMax(root->right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Function to find sum of max and min
// elements in the Binary Tree
int findSum(int max , int min)
{
return max + min;
}
// Function to find product of max and min
// elements in the Binary Tree
int findProduct(int max, int min)
{
return max*min;
}
// Driver Code
int main()
{
// Create Binary Tree
Node* NewRoot = NULL;
Node* root = new Node(2);
root->left = new Node(7);
root->right = new Node(5);
root->left->right = new Node(6);
root->left->right->left = new Node(1);
root->left->right->right = new Node(11);
root->right->right = new Node(9);
root->right->right->left = new Node(4);
int max = findMax(root);
int min = findMin(root);
cout << "Sum of Maximum and Minimum element is " <<
findSum(max,min);
cout << "\nProduct of Maximum and Minimum element is " <<
findProduct(max,min);
return 0;
}
// This code is contributed by rathbhupendra
C
// C program to find sum and product of
// maximum and minimum in a Binary Tree
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// A tree node
struct Node {
int data;
struct Node *left, *right;
};
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Function to return minimum value
// in a given Binary Tree
int findMin(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MAX;
// Return minimum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMin(root->left);
int rres = findMin(root->right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
// Function to returns maximum value
// in a given Binary Tree
int findMax(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MIN;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMax(root->left);
int rres = findMax(root->right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Function to find sum of max and min
// elements in the Binary Tree
int findSum(int max , int min)
{
return max + min;
}
// Function to find product of max and min
// elements in the Binary Tree
int findProduct(int max, int min)
{
return max*min;
}
// Driver Code
int main(void)
{
// Create Binary Tree
struct Node* NewRoot = NULL;
struct Node* root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
int max = findMax(root);
int min = findMin(root);
printf("Sum of Maximum and Minimum element is %d",
findSum(max,min));
printf("\nProduct of Maximum and Minimum element is %d",
findProduct(max,min));
return 0;
}
Java
// JAVA program to find sum and product of
// maximum and minimum in a Binary Tree
import java.util.*;
class GFG
{
// A tree node
static class Node
{
public int data;
Node left, right;
/* Constructor that allocates
a new node with the given data
and null left and right pointers. */
Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to return minimum value
// in a given Binary Tree
static int findMin(Node root)
{
// Base case
if (root == null)
return Integer.MAX_VALUE;
// Return minimum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root.data;
int lres = findMin(root.left);
int rres = findMin(root.right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
// Function to returns maximum value
// in a given Binary Tree
static int findMax(Node root)
{
// Base case
if (root == null)
return Integer.MIN_VALUE;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root.data;
int lres = findMax(root.left);
int rres = findMax(root.right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Function to find sum of max and min
// elements in the Binary Tree
static int findSum(int max , int min)
{
return max + min;
}
// Function to find product of max and min
// elements in the Binary Tree
static int findProduct(int max, int min)
{
return max * min;
}
// Driver Code
public static void main(String[] args)
{
// Create Binary Tree
Node root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.right = new Node(6);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
int max = findMax(root);
int min = findMin(root);
System.out.print("Sum of Maximum and Minimum element is " +
findSum(max, min));
System.out.print("\nProduct of Maximum and Minimum element is " +
findProduct(max, min));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to find sum and product of
# maximum and minimum in a Binary Tree
_MIN=-2147483648
_MAX=2147483648
# Helper function that allocates a new
# node with the given data and None left
# and right pointers.
class newNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to return minimum value
# in a given Binary Tree
def findMin(root):
# Base case
if (root == None):
return _MAX
# Return minimum of 3 values:
# 1) Root's data 2) Max in Left Subtree
# 3) Max in right subtree
res = root.data
lres = findMin(root.left)
rres = findMin(root.right)
if (lres < res):
res = lres
if (rres < res):
res = rres
return res
# Function to returns maximum value
# in a given Binary Tree
def findMax( root):
# Base case
if (root == None):
return _MIN
""" Return maximum of 3 values:
1) Root's data 2) Max in Left Subtree
3) Max in right subtree"""
res = root.data
lres = findMax(root.left)
rres = findMax(root.right)
if (lres > res):
res = lres
if (rres > res):
res = rres
return res
# Function to find sum of max and min
# elements in the Binary Tree
def findSum( max , min):
return max + min
# Function to find product of max and min
# elements in the Binary Tree
def findProduct( max, min):
return max*min
# Driver Code
if __name__ == '__main__':
""" Create binary Tree """
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
max = findMax(root);
min = findMin(root);
print("Sum of Maximum and " +
"Minimum element is ",
findSum(max,min))
print("Product of Maximum and" +
"Minimum element is",
findProduct(max,min))
# This code is contributed
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program to find sum and product of
// maximum and minimum in a Binary Tree
using System;
class GFG
{
// A tree node
class Node
{
public int data;
public Node left, right;
/* Constructor that allocates
a new node with the given data
and null left and right pointers. */
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
};
// Function to return minimum value
// in a given Binary Tree
static int findMin(Node root)
{
// Base case
if (root == null)
return int.MaxValue;
// Return minimum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root.data;
int lres = findMin(root.left);
int rres = findMin(root.right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
// Function to returns maximum value
// in a given Binary Tree
static int findMax(Node root)
{
// Base case
if (root == null)
return int.MinValue;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root.data;
int lres = findMax(root.left);
int rres = findMax(root.right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Function to find sum of max and min
// elements in the Binary Tree
static int findSum(int max , int min)
{
return max + min;
}
// Function to find product of max and min
// elements in the Binary Tree
static int findProduct(int max, int min)
{
return max * min;
}
// Driver Code
public static void Main(String[] args)
{
// Create Binary Tree
Node root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.right = new Node(6);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
int max = findMax(root);
int min = findMin(root);
Console.Write("Sum of Maximum and " +
"Minimum element is " +
findSum(max, min));
Console.Write("\nProduct of Maximum and " +
"Minimum element is " +
findProduct(max, min));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript program to find sum and product of
// maximum and minimum in a Binary Tree
// A tree node
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
/*
* Constructor that allocates a new node with the given data and null left and
* right pointers.
*/
// Function to return minimum value
// in a given Binary Tree
function findMin(root) {
// Base case
if (root == null)
return Number.MAX_VALUE;
// Return minimum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
var res = root.data;
var lres = findMin(root.left);
var rres = findMin(root.right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
// Function to returns maximum value
// in a given Binary Tree
function findMax(root) {
// Base case
if (root == null)
return Number.MIN_VALUE;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
var res = root.data;
var lres = findMax(root.left);
var rres = findMax(root.right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Function to find sum of max and min
// elements in the Binary Tree
function findSum(max , min) {
return max + min;
}
// Function to find product of max and min
// elements in the Binary Tree
function findProduct(max , min) {
return max * min;
}
// Driver Code
// Create Binary Tree
var root = new Node(2);
root.left = new Node(7);
root.right = new Node(5);
root.left.right = new Node(6);
root.left.right.left = new Node(1);
root.left.right.right = new Node(11);
root.right.right = new Node(9);
root.right.right.left = new Node(4);
var max = findMax(root);
var min = findMin(root);
document.write("Sum of Maximum and Minimum element is "
+ findSum(max, min));
document.write("<br/>Product of Maximum and Minimum element is "
+ findProduct(max, min));
// This code contributed by Rajput-Ji
</script>
OutputSum of Maximum and Minimum element is 12
Product of Maximum and Minimum element is 11
Time Comlexity :-O(N)
To find the maximum and minimum elements in a binary tree, we can perform a simple depth-first search traversal of the tree, keeping track of the current maximum and minimum values as we visit each node. The time complexity of this traversal is O(n), where n is the number of nodes in the tree, since we need to visit each node exactly once.
Space Complexity:- O(h)The space complexity for finding the maximum and minimum elements in a binary tree and calculating their sum and product can be expressed as O(h), where h is the height of the tree. This is because the space used by the algorithm is proportional to the maximum number of nodes that are simultaneously on the call stack during the recursive traversal of the tree
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