Bugs: One good thing about them is they keep on inspiring even when you don't want to be.

Friday, May 1, 2015

Implementing Binary Search Tree in Java

I believe we all know what is a Binary Search Tree (also called ordered tree). I will explain the step-by-step implementation of BST in Java. First of all we will need a node class which will store data/info to be stored in node, parent of node, left and right child. We can also create a static nested class for that as well because this class will not be used by any other class. I will go with a separate class as it will keep the code clean and will also be easy to explain.

We want to be able to store any thing inside node (String, Integer and even our own class objects) and for that I would have used generics, also we want data stored in Node class comparable so we have used:

Node<T extends Comparable<T>&gt;

Next we will declare an interface ITree which will define the methods to be implemented by BST later on:

We have also declared two protected fields (as we want them available in derived classes as well) root and size of the tree. Next task is to provide the method implementations. We will consider insert first and will write two methods to insert a node to left or right of a parent.

This completes the insertion functionality. Next we will work upon search functionality where it will search for a value in the tree. If the value is less than the value at current node it will go left else it will go right (assumption is we don't have duplicate).

Next we can work on deletion of a node but before that we need to figure out which node will replace it. We don't have any concern if the node to be deleted has zero or one children, but in case it has both left and right children then we need to design our code carefully. In case node has both children we can delete the node and replace it with either rightmost (largest) child from left sub tree or leftmost (smallest) child from right sub tree. If we keep on using only one of these strategy then it can lead to skewed tree quickly.

Now after getting the replacement node we need to perform deletion. We need to update children of node to be deleted with new parent, update left and right child of replacement node and also update its parent. The method below does that: