Find Maximum or Minimum in Binary Tree

Problem Statement:

Given a binary tree root node, you need to find the minimum and maximum value of the nodes.

Consider the image below:

Minimum value is 7 and maximum value is 30.

Solution:

We can solve this problem by traversing the tree and checking the value with min and max variables.

Initially assign minimum and maximum values as below:

int maximum = INT_MIN;
int minimum = INT_MAX;

Solution in C++

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

int maximum = INT_MIN;
int minimum = INT_MAX;

void get_min_max_value(Node* node) 
{ 
      if (node == NULL) 
      {
          return;
      }

    if (node->data > maximum) 
    {
      maximum = node->data;
    }
    
    if (node->data < minimum) 
    {
      minimum = node->data;
    }

    get_min_max_value(node->left);
    get_min_max_value(node->right);
} 


int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    get_min_max_value(root);
    cout<<"Minimum value is = " <<minimum<<" maximum value is = "<<maximum<<endl;
    return 0;  
}  

Output:

Minimum value is = 7 maximum value is = 30

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *