Implementing a Binary Search Tree in JavaScript

Tree Data Structure

A tree is a collection of nodes connected by some edges. Conventionally, each node of a tree holds some data and reference to its children.

Binary Search Tree

Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right.

For instance, visual representation of a valid BST is −

     25
/   \
20   36
/ \   / \
10 22 30 40

Let’s now implement our very own Binary Search Tree in JavaScript language.

Step 1: The Node Class

This class will represent a single node present at various points in the BST. A BST is nothing but a collection of nodes storing data and child references placed according to the rules described above.

class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};

To create a new Node instance, we can call this class like this with some data −

const newNode = new Node(23);

This will create a new Node instance with data set to 23 and left and right reference both being null.

Step 2: The Binary Search Tree Class:

class BinarySearchTree{
constructor(){
this.root = null;
};
};

This will create the Binary Search Tree class which we can call with the new keyword to make a tree instance.

Now as we are done with the basic stuff let’s move on to inserting a new node at the right place (according to the rules of BST described in definition).

Step 3: Inserting a Node in BST

class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};

Full Binary Search Tree Code:

class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
constructor(){
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);

Updated on: 03-Mar-2021

3K+ Views