Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print Binary Search Tree in Min Max Fashion
Next article icon

Find maximum (or minimum) in Binary Tree

Last Updated : 27 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Binary Tree, find the maximum(or minimum) element in it. For example, maximum in the following Binary Tree is 9.

1T

Recommended Practice
Max and min element in Binary Tree
Try It!

In Binary Search Tree, we can find maximum by traversing right pointers until we reach the rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So the idea is to traverse the given tree and for every node return maximum of 3 values. 

  1. Node’s data.
  2. Maximum in node’s left subtree.
  3. Maximum in node’s right subtree.

Below is the implementation of above approach. 

C++




// C++ program to find 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;
    }
};
 
// 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;
}
 
// Driver Code
int main()
{
    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);
 
    // Function call
    cout << "Maximum element is " << findMax(root) << endl;
 
    return 0;
}
 
// This code is contributed by
// rathbhupendra
 
 

C




// C program to find 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);
}
 
// 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;
}
 
// Driver code
int main(void)
{
    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);
 
    // Function call
    printf("Maximum element is %d \n", findMax(root));
 
    return 0;
}
 
 

Java




// Java code to Find maximum (or minimum) in
// Binary Tree
 
// A binary tree node
class Node {
    int data;
    Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
class BinaryTree {
    Node root;
 
    // Returns the max value in a binary tree
    static int findMax(Node node)
    {
        if (node == null)
            return Integer.MIN_VALUE;
 
        int res = node.data;
        int lres = findMax(node.left);
        int rres = findMax(node.right);
 
        if (lres > res)
            res = lres;
        if (rres > res)
            res = rres;
        return res;
    }
 
    /* Driver code */
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(2);
        tree.root.left = new Node(7);
        tree.root.right = new Node(5);
        tree.root.left.right = new Node(6);
        tree.root.left.right.left = new Node(1);
        tree.root.left.right.right = new Node(11);
        tree.root.right.right = new Node(9);
        tree.root.right.right.left = new Node(4);
 
        // Function call
        System.out.println("Maximum element is "
                           + tree.findMax(tree.root));
    }
}
 
// This code is contributed by Kamal Rawal
 
 

Python3




# Python3 program to find maximum
# and minimum in a Binary Tree
 
# A class to create a new node
 
 
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Returns maximum value in a
# given Binary Tree
 
 
def findMax(root):
 
    # Base case
    if (root == None):
        return float('-inf')
 
    # 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
 
 
# Driver Code
if __name__ == '__main__':
    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)
 
    # Function call
    print("Maximum element is",
          findMax(root))
 
# This code is contributed by PranchalK
 
 

C#




// C# code to Find maximum (or minimum) in
// Binary Tree
using System;
 
// A binary tree node
public class Node {
    public int data;
    public Node left, right;
 
    public Node(int data)
    {
        this.data = data;
        left = right = null;
    }
}
 
public class BinaryTree {
    public Node root;
 
    // Returns the max value in a binary tree
    public static int findMax(Node node)
    {
        if (node == null) {
            return int.MinValue;
        }
 
        int res = node.data;
        int lres = findMax(node.left);
        int rres = findMax(node.right);
 
        if (lres > res) {
            res = lres;
        }
        if (rres > res) {
            res = rres;
        }
        return res;
    }
 
    /* Driver code */
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(2);
        tree.root.left = new Node(7);
        tree.root.right = new Node(5);
        tree.root.left.right = new Node(6);
        tree.root.left.right.left = new Node(1);
        tree.root.left.right.right = new Node(11);
        tree.root.right.right = new Node(9);
        tree.root.right.right.left = new Node(4);
 
        // Function call
        Console.WriteLine("Maximum element is "
                          + BinaryTree.findMax(tree.root));
    }
}
 
// This code is contributed by Shrikant13
 
 

Javascript




<script>
 
    // Javascript code to Find maximum (or minimum)
    // in Binary Tree
     
    let root;
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
   
    // Returns the max value in a binary tree
    function findMax(node)
    {
        if (node == null)
            return Number.MIN_VALUE;
   
        let res = node.data;
        let lres = findMax(node.left);
        let rres = findMax(node.right);
   
        if (lres > res)
            res = lres;
        if (rres > res)
            res = rres;
        return res;
    }
     
    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);
 
    // Function call
    document.write("Maximum element is "
                       + findMax(root));
     
</script>
 
 
Output
Maximum element is 11

Time Complexity: O(N), where N is number of nodes as every node of tree is traversed once by findMax() and findMin().
Auxiliary Space: O(N) , Recursive call for each node tree considered as stack space.

 Similarly, we can find the minimum element in a Binary tree by comparing three values. Below is the function to find a minimum in Binary Tree. 

C++




int findMin(Node *root)
    {
        //code
        if(root==NULL)
     {
         return INT_MAX;
     }
       int res=root->data;
       int left=findMin(root->left);
       int right=findMin(root->right);
       if(left<res)
       {
           res=left;
       }
       if(right<res)
       {
           res=right;
       }
       return res;
    }
 
 

C




// Returns 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;
}
 
 

Java




// Returns the min value in a binary tree
static int findMin(Node node)
{
    if (node == null)
        return Integer.MAX_VALUE;
 
    int res = node.data;
    int lres = findMin(node.left);
    int rres = findMin(node.right);
 
    if (lres < res)
        res = lres;
    if (rres < res)
        res = rres;
    return res;
}
 
 

Python3




# Returns the min value in a binary tree
 
def find_min_in_BT(root):
    if root is None:
        return float('inf')
    res = root.data
    lres = find_min_in_BT(root.leftChild)
    rres = find_min_in_BT(root.rightChild)
    if lres < res:
        res = lres
    if rres < res:
        res = rres
    return res
 
# This code is contributed by Subhajit Nandi
 
 

C#




// Returns the min value in a binary tree
public static int findMin(Node node)
{
    if (node == null)
        return int.MaxValue;
 
    int res = node.data;
    int lres = findMin(node.left);
    int rres = findMin(node.right);
 
    if (lres < res)
        res = lres;
    if (rres < res)
        res = rres;
    return res;
}
 
// This code is contributed by Code_Mech
 
 

Javascript




<script>
 
      // Returns the min value in a binary tree
      function findMin(node) {
        if (node == null) return 2147483647;
 
        var res = node.data;
        var lres = findMin(node.left);
        var rres = findMin(node.right);
 
        if (lres < res) res = lres;
        if (rres < res) res = rres;
        return res;
      }
       
</script>
 
 

Complexity Analysis:

Time Complexity: O(N).
In the recursive function calls, every node of the tree is processed once and hence the complexity due to the function is O(N) if there are total N nodes in the tree. Therefore, the time complexity is O(N).

Space Complexity: O(N).
Recursive call is happening. The every node is processed once and considering the stack space, the space complexity will be O(N).



Next Article
Print Binary Search Tree in Min Max Fashion
author
kartik
Improve
Article Tags :
  • DSA
  • Tree
Practice Tags :
  • Tree

Similar Reads

  • Find maximum vertical sum in binary tree
    Given a binary tree, find the maximum vertical level sum in binary tree. Examples: Input : 3 / \ 4 6 / \ / \ -1 -2 5 10 \ 8 Output : 14Vertical level having nodes 6 and 8 has maximumvertical sum 14. Input : 1 / \ 5 8 / \ \ 2 -6 3 \ / -1 -4 \ 9Output : 4 A simple solution is to first find vertical le
    9 min read
  • Maximum number in Binary tree of binary values
    Given a binary tree consisting of nodes, each containing a binary value of either 0 or 1, the task is to find the maximum decimal number that can be formed by traversing from the root to a leaf node. The maximum number is achieved by concatenating the binary values along the path from the root to a
    6 min read
  • Print Binary Search Tree in Min Max Fashion
    Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion. What is min-max fashion? A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on. Examples: Input: 100 / \ 20 500 / \ 10 30 \ 40 Outp
    10 min read
  • Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
  • Sum and Product of maximum and minimum element in Binary Tree
    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
    12 min read
  • Finding Minimum Steps in Special Binary Tree
    Given two integer values (i and j) as input representing two nodes of a special binary tree. The special binary tree has this property that the root node's value is always 1 and for every node, its left child will be the node's value * 3, and the right child will be ( node's value * 3) + 1. The give
    8 min read
  • Minimum in a Binary Search Tree
    Given the root of a Binary Search Tree. The task is to find the minimum valued element in this given BST. Example: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2 Table of Content [Naive Approach] Using In
    12 min read
  • Find minimum in K Dimensional Tree
    We strongly recommend to refer below post as a prerequisite of this. K Dimensional Tree | Set 1 (Search and Insert) In this post find minimum is discussed. The operation is to find minimum in the given dimension. This is especially needed in delete operation. For example, consider below KD Tree, if
    13 min read
  • Minimum valued node having maximum depth in an N-ary Tree
    Given a tree of N nodes, the task is to find the node having maximum depth starting from the root node, taking the root node at zero depth. If there are more than 1 maximum depth node, then find the one having the smallest value. Examples: Input: 1 / \ 2 3 / \ 4 5 Output: 4 Explanation: For this tre
    5 min read
  • Find Mode in Binary Search tree
    Given a Binary Search Tree, find the mode of the tree. Note: Mode is the value of the node which has the highest frequency in the binary search tree. Examples: Input: 100 / \ 50 160 / \ / \ 50 60 140 170 Output: The mode of BST is 50Explanation: 50 is repeated 2 times, and all other nodes occur only
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences