
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Searching for Minimum and Maximum Values in a 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; }
Advertisements