This is a sample implementation of a Binary Serach Tree in JavaScript. Right now it is a work in progress, please keep looking for updates for this post, as I will keep working on it.
There will be a graphical representation of the tree in the are below that you can use to visualize the operations as I keep progressing in this code.
First we have to define the basic piece, and that is going to be a Node:
The JavaScript constructor takes a value to store in the current node as the value, and also sets the pointers to the left and right nodes as null. This is important to make sure the variables don’t remain as undefined and also that they exist when accessing them from other methods.
As for the methods, let’s start by implementing the insert. The core of the algorithm is to check if the new data has to go either to the left, or to the right, and then call the same insert recursively from the chosen node, like the code below that returns a boolean value to indicate whether the new value was inserted or not: