Traversal with Current Maximum/Minimum - O(n) Time and O(h) Space
The idea is to traverse the binary tree recursively and keep updating the current maximum and minimum values whenever a node is visited.
Working of Approach:
Initialize maximum as INT_MIN and minimum as INT_MAX.
Traverse the binary tree using DFS.
Update the maximum and minimum using the current node's value.
Continue the traversal for the left and right subtrees.
After the traversal, return the final maximum and minimum values.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of a Binary Tree NodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// DFS traversal to update maximum and minimum valuesvoiddfs(Node*root,int&mx,int&mn){// Base Caseif(root==nullptr)return;// Update maximum and minimum valuesmx=max(mx,root->data);mn=min(mn,root->data);// Recur for left and right subtreesdfs(root->left,mx,mn);dfs(root->right,mx,mn);}// Function to find the maximum elementintfindMax(Node*root){intmx=INT_MIN;intmn=INT_MAX;dfs(root,mx,mn);returnmx;}// Function to find the minimum elementintfindMin(Node*root){intmx=INT_MIN;intmn=INT_MAX;dfs(root,mx,mn);returnmn;}intmain(){// Construct the binary tree// 6// / \ // 5 8// /// 2Node*root=newNode(6);root->left=newNode(5);root->right=newNode(8);root->left->left=newNode(2);cout<<findMax(root)<<" ";cout<<findMin(root);return0;}
Java
importjava.util.*;// Structure of a Binary Tree NodeclassNode{publicintdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}publicclassGFG{// DFS traversal to update maximum and minimum valuesstaticvoiddfs(Noderoot,int[]mx,int[]mn){// Base Caseif(root==null)return;// Update maximum and minimum valuesmx[0]=Math.max(mx[0],root.data);mn[0]=Math.min(mn[0],root.data);// Recur for left and right subtreesdfs(root.left,mx,mn);dfs(root.right,mx,mn);}// Function to find the maximum elementstaticintfindMax(Noderoot){int[]mx={Integer.MIN_VALUE};int[]mn={Integer.MAX_VALUE};dfs(root,mx,mn);returnmx[0];}// Function to find the minimum elementstaticintfindMin(Noderoot){int[]mx={Integer.MIN_VALUE};int[]mn={Integer.MAX_VALUE};dfs(root,mx,mn);returnmn[0];}publicstaticvoidmain(String[]args){// Construct the binary tree// 6// / \// 5 8// /// 2Noderoot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);System.out.print(findMax(root)+" ");System.out.print(findMin(root));}}
Python
# Structure of a Binary Tree NodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# DFS traversal to update maximum and minimum valuesdefdfs(root,mx,mn):# Base CaseifrootisNone:return# Update maximum and minimum valuesmx[0]=max(mx[0],root.data)mn[0]=min(mn[0],root.data)# Recur for left and right subtreesdfs(root.left,mx,mn)dfs(root.right,mx,mn)# Function to find the maximum elementdeffindMax(root):mx=[float('-inf')]mn=[float('inf')]dfs(root,mx,mn)returnmx[0]# Function to find the minimum elementdeffindMin(root):mx=[float('-inf')]mn=[float('inf')]dfs(root,mx,mn)returnmn[0]if__name__=='__main__':# Construct the binary tree# 6# / \# 5 8# /# 2root=Node(6)root.left=Node(5)root.right=Node(8)root.left.left=Node(2)print(findMax(root),end=' ')print(findMin(root))
C#
usingSystem;// Structure of a Binary Tree NodepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGFG{// DFS traversal to update maximum and minimum valuesstaticvoidDFS(Noderoot,refintmx,refintmn){// Base Caseif(root==null)return;// Update maximum and minimum valuesmx=Math.Max(mx,root.data);mn=Math.Min(mn,root.data);// Recur for left and right subtreesDFS(root.left,refmx,refmn);DFS(root.right,refmx,refmn);}// Function to find the maximum elementstaticintfindMax(Noderoot){intmx=int.MinValue;intmn=int.MaxValue;DFS(root,refmx,refmn);returnmx;}// Function to find the minimum elementstaticintfindMin(Noderoot){intmx=int.MinValue;intmn=int.MaxValue;DFS(root,refmx,refmn);returnmn;}publicstaticvoidMain(){// Construct the binary tree// 6// / \// 5 8// /// 2Noderoot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);Console.Write(findMax(root)+" ");Console.Write(findMin(root));}}
JavaScript
// Structure of a Binary Tree NodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// DFS traversal to update maximum and minimum valuesfunctiondfs(root,mx,mn){// Base Caseif(root===null)return;// Update maximum and minimum valuesmx[0]=Math.max(mx[0],root.data);mn[0]=Math.min(mn[0],root.data);// Recur for left and right subtreesdfs(root.left,mx,mn);dfs(root.right,mx,mn);}// Function to find the maximum elementfunctionfindMax(root){letmx=[Number.NEGATIVE_INFINITY];letmn=[Number.POSITIVE_INFINITY];dfs(root,mx,mn);returnmx[0];}// Function to find the minimum elementfunctionfindMin(root){letmx=[Number.NEGATIVE_INFINITY];letmn=[Number.POSITIVE_INFINITY];dfs(root,mx,mn);returnmn[0];}// Driver Code// Construct the binary tree// 6// / \// 5 8// /// 2letroot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);console.log(findMax(root)+" ");console.log(findMin(root));
Output
8 2
Separate Traversals for Max and Min - O(n) Time and O(h) Space
The idea is to recursively find the maximum (or minimum) value in the left and right subtrees and combine them with the current node's value to get the answer for the current subtree.
Working of Approach:
If the current node is NULL, return INT_MIN for maximum and INT_MAX for minimum.
Recursively find the answer for the left subtree.
Recursively find the answer for the right subtree.
Return the maximum (or minimum) among the current node and both subtree results.
The root call returns the maximum and minimum values of the entire tree.
Let us understand with an example: Input: root[] = [6, 5, 8, 2]
Start from the root node (6). The recursion explores both the left and right subtrees before computing the maximum and minimum values.
In the left subtree, nodes 5 and 2 are visited. The maximum returned is 5 and the minimum returned is 2.
In the right subtree, node 8 is visited. It returns 8 as both the maximum and minimum for that subtree.
At the root, findMax() computes max(6, 5, 8) = 8, while findMin() computes min(6, 2, 8) = 2.
Hence, the maximum element in the tree is 8 and the minimum element is 2.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of a Binary Tree NodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Function to find the maximum value in a binary tree.intfindMax(Node*root){// If root is null, return INT_MIN as there is no value to compare.if(root==nullptr){returnINT_MIN;}// Return the maximum value among root's data and the maximum values// in its left and right subtrees.returnmax({root->data,findMax(root->left),findMax(root->right)});}// Function to find the minimum value in a binary tree.intfindMin(Node*root){// If root is null, return INT_MAX as there is no value to compare.if(root==nullptr){returnINT_MAX;}// Return the minimum value among root's data and the minimum values// in its left and right subtrees.returnmin({root->data,findMin(root->left),findMin(root->right)});}intmain(){// Construct the binary tree// 6// / \ // 5 8// /// 2Node*root=newNode(6);root->left=newNode(5);root->right=newNode(8);root->left->left=newNode(2);cout<<findMax(root)<<" ";cout<<findMin(root);return0;}
Java
importjava.util.Arrays;// Structure of a Binary Tree NodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGFG{// Function to find the maximum value in a binary tree.publicstaticintfindMax(Noderoot){// If root is null, return Integer.MIN_VALUE as there is no value to compare.if(root==null){returnInteger.MIN_VALUE;}// Return the maximum value among root's data and the maximum values// in its left and right subtrees.returnArrays.stream(newint[]{root.data,findMax(root.left),findMax(root.right)}).max().getAsInt();}// Function to find the minimum value in a binary tree.publicstaticintfindMin(Noderoot){// If root is null, return Integer.MAX_VALUE as there is no value to compare.if(root==null){returnInteger.MAX_VALUE;}// Return the minimum value among root's data and the minimum values// in its left and right subtrees.returnArrays.stream(newint[]{root.data,findMin(root.left),findMin(root.right)}).min().getAsInt();}publicstaticvoidmain(String[]args){// Construct the binary tree// 6// / \// 5 8// /// 2Noderoot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);System.out.print(findMax(root)+" ");System.out.print(findMin(root));}}
Python
"""Structure of a Binary Tree Node"""classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to find the maximum value in a binary tree.deffindMax(root):# If root is null, return float('-inf') as there is no value to compare.ifrootisNone:returnfloat('-inf')# Return the maximum value among root's data and the maximum values# in its left and right subtrees.returnmax(root.data,findMax(root.left),findMax(root.right))# Function to find the minimum value in a binary tree.deffindMin(root):# If root is null, return float('inf') as there is no value to compare.ifrootisNone:returnfloat('inf')# Return the minimum value among root's data and the minimum values# in its left and right subtrees.returnmin(root.data,findMin(root.left),findMin(root.right))if__name__=='__main__':# Construct the binary tree# 6# / \\# 5 8# /# 2root=Node(6)root.left=Node(5)root.right=Node(8)root.left.left=Node(2)print(findMax(root),end=' ')print(findMin(root))
C#
usingSystem;// Structure of a Binary Tree NodepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}publicclassGFG{// Function to find the maximum value in a binary tree.publicstaticintfindMax(Noderoot){// If root is null, return int.MinValue as there is// no value to compare.if(root==null){returnint.MinValue;}// Return the maximum value among root's data and// the maximum values in its left and right// subtrees.returnMath.Max(root.data,Math.Max(findMax(root.left),findMax(root.right)));}// Function to find the minimum value in a binary tree.publicstaticintfindMin(Noderoot){// If root is null, return int.MaxValue as there is// no value to compare.if(root==null){returnint.MaxValue;}// Return the minimum value among root's data and// the minimum values in its left and right// subtrees.returnMath.Min(root.data,Math.Min(findMin(root.left),findMin(root.right)));}publicstaticvoidMain(){// Construct the binary tree// 6// / \\// 5 8// /// 2Noderoot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);Console.Write(findMax(root)+" ");Console.Write(findMin(root));}}
JavaScript
// Structure of a Binary Tree NodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to find the maximum value in a binary tree.functionfindMax(root){// If root is null, return Number.NEGATIVE_INFINITY as// there is no value to compare.if(root===null){returnNumber.NEGATIVE_INFINITY;}// Return the maximum value among root's data and the// maximum values in its left and right subtrees.returnMath.max(root.data,findMax(root.left),findMax(root.right));}// Function to find the minimum value in a binary tree.functionfindMin(root){// If root is null, return Number.POSITIVE_INFINITY as// there is no value to compare.if(root===null){returnNumber.POSITIVE_INFINITY;}// Return the minimum value among root's data and the// minimum values in its left and right subtrees.returnMath.min(root.data,findMin(root.left),findMin(root.right));}// Driver Code// Construct the binary tree// 6// / \\// 5 8// /// 2constroot=newNode(6);root.left=newNode(5);root.right=newNode(8);root.left.left=newNode(2);console.log(findMax(root)+" ");console.log(findMin(root));