Table of contents
1.
Introduction
2.
Problem Statement
2.1.
Constraints
2.2.
Sample Examples
3.
Approach
3.1.
Algorithm
3.1.1.
To Find LCA
3.2.
Implementation
3.2.1.
Complexity Analysis
4.
Frequently Asked Questions
4.1.
What is LCA?
4.2.
How to perform search operations in BST?
4.3.
What is the benefit of a binary search tree?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Find the Maximum Element Between the Two Nodes of BST

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

BST is a non-linear data structure. It is also known as an ordered or sorted binary tree. BSTs are node-based binary trees. In BST, searching for an element is relatively easy. The node's left subtree contains a value lesser than the node’s value. The node's right subtree contains a value greater than the node’s value.

Find the maximum element between the two nodes of BST

In this article, we will deal with a problem related to BST. We will find the maximum element between the two nodes of BST.

Problem Statement

Ninja wants to take his GF out for dinner. There are many restaurants between his and his GF's home. He wishes for a perfect day. So he wants to visit the hotel with the maximum ratings. Help Ninja to find the one with maximum ratings and make his day memorable.

We have an array of N integers. The array includes the hotel’s ratings. The array also consists of two integers(X, Y), the house no. of ninja and his GF. We will create a BST using the elements from A[0] to A[N-1]. We will find the max element in the path from X to Y.

Constraints

1 <= N <= 3000

1 <= X,Y <= 106

0 <= value <= 106

N  denotes the no. of nodes in the BST(elements in the given array). X, Y denotes two integers, and value denotes the value of each node in the tree.

We will see some sample examples before we get too deep into the solution.

Sample Examples

Example 1: 

Input:

Input1

N = 8, X = 18, and Y = 28.

Output: 

Maximum element between given nodes= 32
You can also try this code with Online C++ Compiler
Run Code

 

Explanation: 

After constructing BST from the given array, we get 32 as the maximum element.
You can also try this code with Online C++ Compiler
Run Code
BST1

 

Example 2:

Input:

Input2

N = 9, X = 1, and Y = 11.

Output: 

Maximum element between given nodes= 13
You can also try this code with Online C++ Compiler
Run Code

 

Explanation: 

After constructing BST from the given array, we get 13 as the maximum element between 1 and 11.
You can also try this code with Online C++ Compiler
Run Code
BST2

Approach

We will use a two-step process to find the maximum element.
a.) Find the LCA of the two nodes.

b.) Find the maximum element between the LCA and the greater of X and Y values.

Let’s see the algorithm:

Algorithm

  1. Find the LCA of X and Y.
  2. Initialise a variable MAX by -1 if no element exists in the path from X to Y.
  3. Traverse the tree from LCA to X and keep updating the MAX such that if the current value is greater than ‘MAX,’ the current value will become ‘MAX.’
  4. Similarly, traverse the tree from LCA to Y and keep updating the ‘MAX.’
  5. Return the ‘MAX.’
     

To Find LCA

  1. Create a recursive function that requires the BST's root and X and Y values.
  2. Begin with the root node.
  3. Compare the current node's value to the nodes X and Y values.
    • If value(current node) < value(Node X & Y), X and Y lies in right subtree. We will call the recursive function for the right subtree.
    • If value(current node) > value(Node X & Y), X and Y lies in left subtree. We will call the recursive function for the left subtree.
    • If the above cases are false, return the current node value as LCA.

Implementation

This is the C++ code for our algorithm.

#include <bits/stdc++.h>
using namespace std;
struct node {
   int data;
   struct node* left;
   struct node* right;
};


//Creating a new node.
node *createNode(int i) {
   node *r = new node();
   r -> data = i;
   r -> left = NULL;
   r -> right = NULL;
   return r;
}


// Function to insert nodes in BST.
void InsertNode(struct node *root, int n) {
   node *p = root, *q = NULL;
   while (p != NULL) {
      q = p;
      if (p -> data < n) {
         p = p -> right;
      } else {
         p = p -> left;
      }
   }
   if (q == NULL) {
      p = createNode(n);
   } else {
      if (q -> data < n) {
         q -> right = createNode(n); } else {
            q -> left = createNode(n);
      }
   }
}


//Function to return maximum element.
int MaxElementInPath(node *q, int i) {
   node *p = q;
   int MAX = -1;


//Returning maximum value.
   while (p -> data != i) {
      if (p -> data > i) {
         MAX = max(MAX, p -> data);
         p = p -> left;
      } else {
         MAX = max(MAX, p -> data);
         p = p -> right;
      }
   }
   return max(MAX, i);
}


//MAximum element between two nodes.
int MaxElement(struct node *root, int x, int y) {
   node *r = root;


//Finding the LCA of nodes x and y.
   while ((x < r -> data && y < r -> data) || (x > r ->
   data && y > r -> data)) {
      if (x < r -> data && y < r -> data) {
         r = r -> left;
      } else if (x > r -> data && y > r -> data) {
         r = r -> right;
      }
   }
   return max(MaxElementInPath(r, x), MaxElementInPath(r, y));
}
int main() {
   int A[] = {25, 32, 23, 14, 28, 36, 10, 18}; int a = 18, b = 28;
   int n = sizeof(A) / sizeof(A[0]);
   struct node *root = createNode(A[0]);
   for (int i = 1; i < n; i++) InsertNode(root, A[i]);
   cout << "Maximum element between given nodes= " << MaxElement(root, a, b) << endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output: 

Maximum element between given nodes= 32
You can also try this code with Online C++ Compiler
Run Code

 

Complexity Analysis

Time Complexity: The time complexity of this algorithm is O(h), where h is the tree's height. Since we are traversing the tree to find the maxim element. The complexity of traversing a BST is O(h).

Space Complexity: The space complexity is O(n), where n is the no of nodes. This complexity is due to the extra space required to create and store the BST.

Frequently Asked Questions

What is LCA?

LCA stands for Lowest Common Ancestor. In a rooted tree, the lowest (deepest) node that is an ancestor of both x and y is known as the LCA of the two nodes, x and y. An ancestor of node x can be any node on the path from the root to node x in a rooted tree. It also includes the node x value itself.

How to perform search operations in BST?

Search from the root node whenever an element has to be searched. Search for the element in the left subtree if the data is smaller than the key value. If not, look for the element in the right subtree. For every node, use the same algorithm.

What is the benefit of a binary search tree?

A binary search tree is a data structure that offers an effective way to iterate elements while providing quick insertion, removal, and lookup properties. We can always keep the cost of these functions O(log n). It is very effective and easy to implement.

Conclusion

We ran through the solution of finding maximum elements between two nodes in a BST. We hope this blog helped you.

This article is related to the binary search tree, so it is recommended to visit our curated section of BST at the Coding Ninjas Studio library, where you can learn:


You can also visit our curated sections of AVL treeGraphTrieDynamic programming, and many more.

Here are some of the widespread binary tree problems for your coding practice:

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

Live masterclass