Java Program to Implement Binary Search Tree

This is a Java Program to implement Binary Search Tree. A binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties:
i) The left subtree of a node contains only nodes with keys less than the node’s key.
ii) The right subtree of a node contains only nodes with keys greater than the node’s key.
iii) The left and right subtree must each also be a binary search tree.
iv) There must be no duplicate nodes.
Generally, the information represented by each node is a record rather than a single data element. However, for sequencing purposes, nodes are compared according to their keys rather than any part of their associated records. The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.

Here is the source code of the Java program to implement Binary Search Tree. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  *  Java Program to Implement Binary Search Tree
  3.  */
  4.  
  5.  import java.util.Scanner;
  6.  
  7.  /* Class BSTNode */
  8.  class BSTNode
  9.  {
  10.      BSTNode left, right;
  11.      int data;
  12.  
  13.      /* Constructor */
  14.      public BSTNode()
  15.      {
  16.          left = null;
  17.          right = null;
  18.          data = 0;
  19.      }
  20.      /* Constructor */
  21.      public BSTNode(int n)
  22.      {
  23.          left = null;
  24.          right = null;
  25.          data = n;
  26.      }
  27.      /* Function to set left node */
  28.      public void setLeft(BSTNode n)
  29.      {
  30.          left = n;
  31.      }
  32.      /* Function to set right node */ 
  33.      public void setRight(BSTNode n)
  34.      {
  35.          right = n;
  36.      }
  37.      /* Function to get left node */
  38.      public BSTNode getLeft()
  39.      {
  40.          return left;
  41.      }
  42.      /* Function to get right node */
  43.      public BSTNode getRight()
  44.      {
  45.          return right;
  46.      }
  47.      /* Function to set data to node */
  48.      public void setData(int d)
  49.      {
  50.          data = d;
  51.      }
  52.      /* Function to get data from node */
  53.      public int getData()
  54.      {
  55.          return data;
  56.      }     
  57.  }
  58.  
  59.  /* Class BST */
  60.  class BST
  61.  {
  62.      private BSTNode root;
  63.  
  64.      /* Constructor */
  65.      public BST()
  66.      {
  67.          root = null;
  68.      }
  69.      /* Function to check if tree is empty */
  70.      public boolean isEmpty()
  71.      {
  72.          return root == null;
  73.      }
  74.      /* Functions to insert data */
  75.      public void insert(int data)
  76.      {
  77.          root = insert(root, data);
  78.      }
  79.      /* Function to insert data recursively */
  80.      private BSTNode insert(BSTNode node, int data)
  81.      {
  82.          if (node == null)
  83.              node = new BSTNode(data);
  84.          else
  85.          {
  86.              if (data <= node.getData())
  87.                  node.left = insert(node.left, data);
  88.              else
  89.                  node.right = insert(node.right, data);
  90.          }
  91.          return node;
  92.      }
  93.      /* Functions to delete data */
  94.      public void delete(int k)
  95.      {
  96.          if (isEmpty())
  97.              System.out.println("Tree Empty");
  98.          else if (search(k) == false)
  99.              System.out.println("Sorry "+ k +" is not present");
  100.          else
  101.          {
  102.              root = delete(root, k);
  103.              System.out.println(k+ " deleted from the tree");
  104.          }
  105.      }
  106.      private BSTNode delete(BSTNode root, int k)
  107.      {
  108.          BSTNode p, p2, n;
  109.          if (root.getData() == k)
  110.          {
  111.              BSTNode lt, rt;
  112.              lt = root.getLeft();
  113.              rt = root.getRight();
  114.              if (lt == null && rt == null)
  115.                  return null;
  116.              else if (lt == null)
  117.              {
  118.                  p = rt;
  119.                  return p;
  120.              }
  121.              else if (rt == null)
  122.              {
  123.                  p = lt;
  124.                  return p;
  125.              }
  126.              else
  127.              {
  128.                  p2 = rt;
  129.                  p = rt;
  130.                  while (p.getLeft() != null)
  131.                      p = p.getLeft();
  132.                  p.setLeft(lt);
  133.                  return p2;
  134.              }
  135.          }
  136.          if (k < root.getData())
  137.          {
  138.              n = delete(root.getLeft(), k);
  139.              root.setLeft(n);
  140.          }
  141.          else
  142.          {
  143.              n = delete(root.getRight(), k);
  144.              root.setRight(n);             
  145.          }
  146.          return root;
  147.      }
  148.      /* Functions to count number of nodes */
  149.      public int countNodes()
  150.      {
  151.          return countNodes(root);
  152.      }
  153.      /* Function to count number of nodes recursively */
  154.      private int countNodes(BSTNode r)
  155.      {
  156.          if (r == null)
  157.              return 0;
  158.          else
  159.          {
  160.              int l = 1;
  161.              l += countNodes(r.getLeft());
  162.              l += countNodes(r.getRight());
  163.              return l;
  164.          }
  165.      }
  166.      /* Functions to search for an element */
  167.      public boolean search(int val)
  168.      {
  169.          return search(root, val);
  170.      }
  171.      /* Function to search for an element recursively */
  172.      private boolean search(BSTNode r, int val)
  173.      {
  174.          boolean found = false;
  175.          while ((r != null) && !found)
  176.          {
  177.              int rval = r.getData();
  178.              if (val < rval)
  179.                  r = r.getLeft();
  180.              else if (val > rval)
  181.                  r = r.getRight();
  182.              else
  183.              {
  184.                  found = true;
  185.                  break;
  186.              }
  187.              found = search(r, val);
  188.          }
  189.          return found;
  190.      }
  191.      /* Function for inorder traversal */
  192.      public void inorder()
  193.      {
  194.          inorder(root);
  195.      }
  196.      private void inorder(BSTNode r)
  197.      {
  198.          if (r != null)
  199.          {
  200.              inorder(r.getLeft());
  201.              System.out.print(r.getData() +" ");
  202.              inorder(r.getRight());
  203.          }
  204.      }
  205.      /* Function for preorder traversal */
  206.      public void preorder()
  207.      {
  208.          preorder(root);
  209.      }
  210.      private void preorder(BSTNode r)
  211.      {
  212.          if (r != null)
  213.          {
  214.              System.out.print(r.getData() +" ");
  215.              preorder(r.getLeft());             
  216.              preorder(r.getRight());
  217.          }
  218.      }
  219.      /* Function for postorder traversal */
  220.      public void postorder()
  221.      {
  222.          postorder(root);
  223.      }
  224.      private void postorder(BSTNode r)
  225.      {
  226.          if (r != null)
  227.          {
  228.              postorder(r.getLeft());             
  229.              postorder(r.getRight());
  230.              System.out.print(r.getData() +" ");
  231.          }
  232.      }     
  233.  }
  234.  
  235.  /* Class BinarySearchTree */
  236.  public class BinarySearchTree
  237.  {
  238.      public static void main(String[] args)
  239.     {                 
  240.         Scanner scan = new Scanner(System.in);
  241.         /* Creating object of BST */
  242.         BST bst = new BST(); 
  243.         System.out.println("Binary Search Tree Test\n");          
  244.         char ch;
  245.         /*  Perform tree operations  */
  246.         do    
  247.         {
  248.             System.out.println("\nBinary Search Tree Operations\n");
  249.             System.out.println("1. insert ");
  250.             System.out.println("2. delete");
  251.             System.out.println("3. search");
  252.             System.out.println("4. count nodes");
  253.             System.out.println("5. check empty"); 
  254.  
  255.             int choice = scan.nextInt();            
  256.             switch (choice)
  257.             {
  258.             case 1 : 
  259.                 System.out.println("Enter integer element to insert");
  260.                 bst.insert( scan.nextInt() );                     
  261.                 break;                          
  262.             case 2 : 
  263.                 System.out.println("Enter integer element to delete");
  264.                 bst.delete( scan.nextInt() );                     
  265.                 break;                         
  266.             case 3 : 
  267.                 System.out.println("Enter integer element to search");
  268.                 System.out.println("Search result : "+ bst.search( scan.nextInt() ));
  269.                 break;                                          
  270.             case 4 : 
  271.                 System.out.println("Nodes = "+ bst.countNodes());
  272.                 break;     
  273.             case 5 :  
  274.                 System.out.println("Empty status = "+ bst.isEmpty());
  275.                 break;            
  276.             default : 
  277.                 System.out.println("Wrong Entry \n ");
  278.                 break;   
  279.             }
  280.             /*  Display tree  */ 
  281.             System.out.print("\nPost order : ");
  282.             bst.postorder();
  283.             System.out.print("\nPre order : ");
  284.             bst.preorder();
  285.             System.out.print("\nIn order : ");
  286.             bst.inorder();
  287.  
  288.             System.out.println("\nDo you want to continue (Type y or n) \n");
  289.             ch = scan.next().charAt(0);                        
  290.         } while (ch == 'Y'|| ch == 'y');               
  291.     }
  292.  }

Binary Search Tree Test
 
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
5
Empty status = true
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
8
 
Post order : 8
Pre order : 8
In order : 8
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
5
 
Post order : 5 8
Pre order : 8 5
In order : 5 8
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
3
 
Post order : 3 5 8
Pre order : 8 5 3
In order : 3 5 8
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
7
 
Post order : 3 7 5 8
Pre order : 8 5 3 7
In order : 3 5 7 8
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
10
 
Post order : 3 7 5 10 8
Pre order : 8 5 3 7 10
In order : 3 5 7 8 10
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
15
 
Post order : 3 7 5 15 10 8
Pre order : 8 5 3 7 10 15
In order : 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
2
 
Post order : 2 3 7 5 15 10 8
Pre order : 8 5 3 2 7 10 15
In order : 2 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
4
Nodes = 7
 
Post order : 2 3 7 5 15 10 8
Pre order : 8 5 3 2 7 10 15
In order : 2 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
24
Search result : false
 
Post order : 2 3 7 5 15 10 8
Pre order : 8 5 3 2 7 10 15
In order : 2 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
7
Search result : true
 
Post order : 2 3 7 5 15 10 8
Pre order : 8 5 3 2 7 10 15
In order : 2 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
2
2 deleted from the tree
 
Post order : 3 7 5 15 10 8
Pre order : 8 5 3 7 10 15
In order : 3 5 7 8 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
8
8 deleted from the tree
 
Post order : 3 7 5 15 10
Pre order : 10 5 3 7 15
In order : 3 5 7 10 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
10
10 deleted from the tree
 
Post order : 3 7 5 15
Pre order : 15 5 3 7
In order : 3 5 7 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
5
5 deleted from the tree
 
Post order : 3 7 15
Pre order : 15 7 3
In order : 3 7 15
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
15
15 deleted from the tree
 
Post order : 3 7
Pre order : 7 3
In order : 3 7
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
3
3 deleted from the tree
 
Post order : 7
Pre order : 7
In order : 7
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
77
Sorry 77 is not present
 
Post order : 7
Pre order : 7
In order : 7
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
7
7 deleted from the tree
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
y
 
Binary Search Tree Operations
 
1. insert
2. delete
3. search
4. count nodes
5. check empty
5
Empty status = true
 
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.