Given a Binary Tree, find the maximum(or minimum) element in it. For example, maximum in the following Binary Tree is 9.
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.Â
- Node’s data.
- Maximum in node’s left subtree.
- 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 nodeclass 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 Treeint 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 Codeint 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 nodestruct Node {Â Â Â Â int data;Â Â Â Â struct Node *left, *right;};Â
// A utility function to create a new nodestruct 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 Treeint 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 codeint 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 nodeclass 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 Codeif __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 Treeusing System;Â
// A binary tree nodepublic 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> |
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 Treeint 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 treestatic 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 treepublic 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).
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

