How to implement Binary Search tree in Java?Posted by Infocampus HR on February 24th, 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. Binary Search tree in JavaHere, 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.
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.
There is a good chance of you discovering that a particular field or method is exposing implementation detail, and should be abstracted in public method. What all this means is, you, a Java developer, must write unit tests. Since it always helps to start smaller, this JUnit tutorial will present another simple JUnit example to show how to write unit test in Java. In this JUnit tutorial, we will implement a linked list in Java and we will write unit test cases for a linked list. For those, who are not familiar with the linked list, it's one of the fundamental data structure to store objects, like an array, which is also used to store object. By the way, there is much difference between linked list and array data structure, which is subject of another blog post, but the main difference is in the way objects are stored. An array needs contiguous memory, while linked list doesn't need that. Like it? Share it!More by this author |