From the course: Data Structures in JavaScript: Trees and Graphs

Binary search tree implementation: search

- [Instructor] In this lesson, we will implement the search operation for A BST. Let's get started. The search method takes in a value, which is a target for the search and returns the node if it exists or null otherwise. Searching is similar to insertion. We start off by setting the current node to be this.root, and our while loop condition is to check if the current node is not null. If the current node matches the target, return true. If the target value is smaller, move left. Else, if larger, move right. If we reached a null node, the while loop will end and we then return false. Let's confirm that the search method works. Here, I have two calls on the BST. One to search for six, which should output true because it exists, and another to search for 42, which should output false because it doesn't exist. Let's run the code. Awesome. With the search operation complete, let's move on to the delete operation, see you there.

Contents