Insertion in Binary Search Tree

(Reading time: 4 minutes)

We'll cover the following...

The Javascript function to add a node in the binary search tree is as follows:

Press + to interact
addNode(data) {
const newNode = new Node(data);
if (!this.root) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
insertNode(node, newNode) {
if (newNode.data < node.data) {
if (!node.left) {
node.left = newNode;
} else {
this.insertNode(node.left, newNode);
}
} else {
if (!node.right) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
}

First, we create our new node. If there is no root in the tree, meaning that there are no nodes at all, the new node is the new root. Otherwise, if the root is already present, we invoke the insertNode function that receives two ...