Searching in a Binary Search Tree (Implementation)
This lesson is about Searching in a Binary Search Tree and how to implement searching functionality in JavaScript.
Introduction #
In this lesson, we’ll implement a search function for binary search trees which will return a node from the tree if the value to be searched matches it. We’ll again implement both an iterative and a recursive solution.
Here is a high-level description of the algorithm:
-
Set the
currentNode
equal to root. -
If the value to be searched is less than the
currentNode
's value, then move on to the left subtree, otherwise move on to the right subtree. -
Repeat until the value at the
currentNode
is equal to the value searched or it becomesnull
. -
Return the
currentNode
.
Iterative Search Implementation #
The implementation of the above algorithm in JavaScript is as follows:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.