Searching for values in an Javascript Binary Search Tree


We're going to use the property of a BST to look up elements in it. Let us look at first an iterative implementation of search − 

Example

searchIter(data) {
   let currNode = this.root;
   while (currNode !== null) {
      if (currNode.data === data) {
         // Found the element!
         return true;
      } else if (data < currNode.data) {
         // Go Left as data is smaller than parent
         currNode = currNode.left;
      } else {
         // Go right as data is greater than parent
         currNode = currNode.right;
      }
   }
   return false;
}

In this function, we start with the root as currNode and check our data compared to the currNode's data. If we find a match we return true, else we continue to iterate in either left or right according to data's relation to currNode's data till we either reach a leaf or find our element.

You can test this using − 

Example

let BST = new BinarySearchTree();
BST.insertIter(10);
BST.insertIter(15);
BST.insertIter(5);
BST.insertIter(50);
BST.insertIter(3);
BST.insertIter(7);
BST.insertIter(12);

console.log(BST.searchIter(2));
console.log(BST.searchIter(12));
console.log(BST.searchIter(50));
console.log(BST.searchIter(-22));
console.log(BST.searchIter(200));

Output

This will give the output −

false
true
true
false
false

Similar to the insert function, the search can be implemented recursively as well. 

searchRec(data) {
   return searchRecHelper(data, this.root);
}

Again, we're going to need to create a helper function that we don't want as a part of the class, so we'll create this function outside of class definition −

Example

function searchRecHelper(data, root) {
   if (root === null) {
      // Reached leaf but didn't find it.
      return false;
   }
   if (data < root.data) {
      return searchRecHelper(data, root.left);
   } else if (data > root.data) {
      return searchRecHelper(data, root.right);
   }
   // This means element is found
   return true;
}

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.searchRec(2));
console.log(BST.searchRec(12));
console.log(BST.searchRec(50));
console.log(BST.searchRec(-22));
console.log(BST.searchRec(200));

Output

This will give the output −

false
true
true
false
false

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 15-Jun-2020

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements