Code: -
//FA19-BSE-079
// ABU BAKAR
class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
Node root;
BinarySearchTree() {
root = null;
void insert(int key) {
root = insertKey(root, key);
// Insert key in the tree
Node insertKey(Node root, int key)
{
// Return a new node if the tree is empty
if (root == null) {
root = new Node(key);
return root;
if (key < root.key)
root.left = insertKey(root.left, key);
else if (key > root.key)
root.right = insertKey(root.right, key);
return root;
void inorder()
inorderRec(root);
void inorderRec(Node root)
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " -> ");
inorderRec(root.right);
void deleteKey(int key) {
root = deleteRec(root, key);
Node deleteRec(Node root, int key)
if (root == null)
return root;
if (key < root.key)
root.left = deleteRec(root.left, key);
else if (key > root.key)
root.right = deleteRec(root.right, key);
else {
// If the node is with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
root.key = minValue(root.right);
root.right = deleteRec(root.right, root.key);
return root;
int minValue(Node root) {
int minv = root.key;
while (root.left != null) {
minv = root.left.key;
root = root.left;
return minv;
public static void main(String[] args)
BinarySearchTree tree = new BinarySearchTree();
tree.insert(94);
tree.insert(82);
tree.insert(83);
tree.insert(18);
tree.insert(40);
tree.insert(97);
tree.insert(110);
tree.insert(91);
tree.insert(32);
tree.insert(96);
tree.insert(99);
System.out.print("\nThe Inorder traversal is: ");
tree.inorder();
System.out.println("\nAfter deleting 82 we have");
tree.deleteKey(82);
System.out.print("Inorder traversal: ");
tree.inorder();
}