Java Program to Search an Element in a Binary Search Tree

This is a java program to search an element using Binary Search Tree. A regular tree traversal algorithm is implemented to search an element. We start from root, if value to be searched is less than root we traverse left, else we check if its greater we traverse right, else it is equal and return true.

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

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

Output:

$ javac Search_Element_BST.java
$ java Search_Element_BST
 
In order traversal of the tree :
3 4 7 17 18 40 46 48 53 54 59 60 74 77 85 91 92 93 95 96 
Enter the element to be searched: 
51
Search result : false

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

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.