Binary search tree pt.2

Daniel Cooper
2 min readJan 25, 2021

--

Welcome to part two of my two-part blog series on Binary search trees! So, last week I went over what trees and binary search trees are, and this week I plan on going over how you can add or find nodes on a binary search tree.

Adding to the binary search tree

If you read my last blog you already know how to Insert a node into a binary search tree if you were to look at a diagram. You just ask these questions “is newNode bigger or smaller than root node?” if bigger go right if smaller go left. Then question two is there a node in this spot? If yes go back to question one and repeat until there is no node in that spot. That being said doing this in code look likes this.

function addNode(rootNode, newNode){
let currentNode = rootNode;
if(newNode.data < rootNode.data){
currentNode = rootNode.left;
if(currentNode){
addNode(currentNode, newNode){
} else {
rootNode.left = newNode;
};
} else if(newNode.data > rootNode.data){
currentNode = rootNode.right;
if(currentNode){
addNode(currentNode, newNode){
} else {
rootNode.right = newNode;
}
}
}

Searching in a binary search tree

Now when we are looking for a node we are just traversing down the tree using the same rules till we find a node equal to the node we are looking for. So, we are just going to follow the same steps we took when we were adding to the tree, but this time we won’t add. The code to do this looks like this.

function nodeSearch(rootNode, data){
if(rootNode === null){
return null;
} else if(data < rootNode.data){
nodeSearch(rootNode.left, data);
} else if(data > rootNode.data){
nodeSearch(rootNode.right, data);
} else {
return node;
}
}

This is the end to my two-part blog this one was a short blog but I hope it helped if you have any questions feel free to ask. I also want to say that this is not all there is to binary search trees there are so many other things you can do.

--

--