Searching for minimum and maximum values in an Javascript Binary Search Tree


In a Binary Search Tree, if we look at the property that the left child is always smaller than the parent, we will find that if we keep iterating towards the left child till we reach a node with no left child, we'll basically find the smallest element in the BST.

Let us implement this function in our code. From now onwards we'll implement only single versions of the function, i.e., either iterative or recursive. In this case, we'll create an iterative function −

Example

getMinVal() {
   if (this.root === null) {
      throw "Empty tree!";
   }
   let currNode = this.root;

   while (currNode.left !== null) {
      currNode = currNode.left;
   }
   return currNode.data;
}

You can test this using −

Example

let BST = new BinarySearchTree();
BST.insertRec(10);
BST.insertRec(15);
BST.insertRec(5);
BST.insertRec(50);
BST.insertRec(3);
BST.insertRec(7);
BST.insertRec(12);
console.log(BST.getMinVal());

Output

This will give the output −

3

Similarly, you can extend this code to write a function called getMaxVal() that returns the max value by iterating over the rightmost child values. We'll just put the code here for you to verify −

Example

getMaxVal() {
if (this.root === null) {
      throw "Empty tree!";
}
let currNode = this.root;

while (currNode.right !== null) {
   currNode = currNode.right;
}
   return currNode.data;
}

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 15-Jun-2020

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements