- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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; }
- Related Articles
- Searching for values in an Javascript Binary Search Tree
- Searching for a query using binary search in JavaScript
- Checking for univalued Binary Search Tree in JavaScript
- Finding minimum absolute difference within a Binary Search Tree in JavaScript
- Binary Search Tree in Javascript
- Binary Search Tree Class in Javascript
- C++ Program to Search for an Element in a Binary Search Tree
- Find maximum (or minimum) in Binary Tree in C++
- Implementing a Binary Search Tree in JavaScript
- Difference between Binary Tree and Binary Search Tree
- Finding Mode in a Binary Search Tree in JavaScript
- Binary Tree to Binary Search Tree Conversion in C++
- Binary Search Tree - Search and Insertion Operations in C++
- C++ Program to Find the Minimum value of Binary Search Tree
- Find the node with minimum value in a Binary Search Tree in C++

Advertisements