How to implement Binary Search tree in Java?

Posted by Infocampus HR on February 26th, 2018

                                      Since its a binary tree, it can only have 0, 1 or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove and search, also known as insert, delete and find. In a BST, all these operations (insert, remove and find) can be performed in O(log(n)) time. The reason for this improvement in speed is because of the unique property of binary search tree, where for each node, the data in the left child is less than (or equal) and the data in the right child is greater than (or equal) to the data in said node.

In Programming interviews, you will see many data structure and algorithmic questions based upon binary search tree e.g. check if a binary tree is a BST or not? Or, write a program to check if BST is balanced or not. In order to solve that problem, you must know how to implement BST in Java.

In this tutorial, I will teach you how to implement a binary search tree in Java, which you can use to solve any binary search tree or binary tree based coding problems.


Binary Search tree in Java

Here, You will learn how to create a binary search tree with integer nodes. I am not using Generics just to keep the code simple but if you like you can extend the problem to use Generics, which will allow you to create a Binary tree of String, Integer, Float or Double. Remember, you make sure that node of BST must implement the Comparable interface. This is what many Java programmer forget when they try to implement binary search tree with Generics.

Here is an implementation of a binary search tree in Java. It's just a structure, we will subsequently add methods to add a node in a binary search tree, delete a node from binary search tree and find a node from BST in the subsequent part of this binary search tree tutorial.

In this implementation, I have created a Node class, which is similar to our linked list node class, which we created when I have shown you how to implement linked list in Java. It has a data element, an integer and a Node reference to point to another node in the binary tree.

I have also created four basic functions, as shown below:

  •  getRoot(), returns the root of binary tree
  •  isEmpty(), to check if binary search tree is empty or not
  •  size(), to find the total number of nodes in a BST
  •  clear(), to clear the BST


For a curious developer who wants to learn advanced data structure in Java, I also recommend checking out Data Structures and Algorithms in Java


Java Program to represent Binary Search Tree or BST

importjava.util.Stack;

/**

 * Java Program to implement a binary search tree. A binary search tree is a

 * sorted binary tree, where value of a node is greater than or equal to its

 * left the child and less than or equal to its right child.

 *

 * @author WINDOWS 8

 *

 */

publicclassBST {

    privatestaticclassNode {

        privateint data;

        privateNode left, right;

        publicNode(intvalue) {

            data = value;

            left = right =null;

        }

    }

    privateNode root;

    publicBST() {

        root =null;

    }

    publicNodegetRoot() {

        return root;

    }

    /**

     * Java function to check if binary tree is empty or not

     * Time Complexity of this solution is constant O(1) for

     * best, average and worst case.

     *

     * @return true if binary search tree is empty

     */

    publicbooleanisEmpty() {

        returnnull== root;

    }

   

    /**

     * Java function to return number of nodes in this binary search tree.

     * Time complexity of this method is O(n)

     * @return size of this binary search tree

     */

    publicintsize() {

        Node current = root;

        int size =0;

        Stack<Node> stack =newStack<Node>();

        while (!stack.isEmpty() || current !=null) {

            if (current !=null) {

                stack.push(current);

                current = current.left;

            } else {

                size++;

                current = stack.pop();

                current = current.right;

            }

        }

        return size;

    }

    /**

     * Java function to clear the binary search tree.

     * Time complexity of this method is O(1)

     */

    publicvoidclear() {

        root =null;

    }

}


That's all in this tutorial about how to implement binary search tree in Java. In this tutorial, you have learned to create the structure of BST using Node class and some basic function. In next couple of tutorials, you will learn some more interesting things with BST e.g. writing a method to add Nodes in BST, this method must make sure that property of binary search tree is not violated. I mean, it first needs to find a right place and then needs to add the element. Subsequently, you will also learn how to search a node in binary search tree.

Further Reading
If you are interested in learning Data structure and Algorithm in Java Programming language then you can following books which have several examples of the tree, linked list, heap and other advanced data structure in Java.

Like it? Share it!


Infocampus HR

About the Author

Infocampus HR
Joined: December 10th, 2016
Articles Posted: 792

More by this author