Binary Search Tree using Collection in DSA Java Part – 2
by TechVidvan Team
Program 1
import java.util.*;
class TestBST
{
public static void main(String args[])
{
TreeSet<Integer>bst=new TreeSet<Integer>();
Scanner scan=new Scanner(System.in);
int choice;
do
{
System.out.println("--------------Binary Search Tree----------------");
System.out.println("1.Create");
System.out.println("2.Display");
System.out.println("3.Search");
System.out.println("4.Remove");
System.out.println("5.Exit");
System.out.println("----------------------------------------------------");
System.out.println("Enter your choice");
choice=scan.nextInt();
switch(choice)
{
case 1:
{
String ch;
int n;
System.out.println("Enter an element");
n=scan.nextInt();
bst.add(n);
System.out.println("Want to continue(Y/N)");
ch=scan.next();
while(ch.toUpperCase().equals("Y"))
{
System.out.println("Enter next element");
n=scan.nextInt();
if(bst.contains(n))
System.out.println("Duplicate elements not allowed");
else
bst.add(n);
System.out.println("Want to continue(Y/N)");
ch=scan.next();
}
break;
}
case 2:
{
if(bst.isEmpty())
System.out.println("No elements in tree");
else
{
System.out.println("Tree Elements: ");
for(Integer t:bst)
{
System.out.println(t);
}
}
break;
}
case 3:
{
if(bst.isEmpty())
System.out.println("Tree is empty......");
else
{
int s;
System.out.println("Enter element for search..");
s=scan.nextInt();
if(bst.contains(s))
System.out.println("Searching success");
else
System.out.println("Searching not success");
}
break;
}
case 4:
{
if(bst.isEmpty())
System.out.println("Tree is empty......");
else
{
int s;
System.out.println("Enter element for remove..");
s=scan.nextInt();
if(bst.remove(s))
System.out.println("Element removed");
else
System.out.println("Element not found");
break;
}
}
case 5: break;
}
}while(choice!=5);
}
}
Tags: Binary Search Treebinary search tree using collectionbinary search tree using collection in dsa javadata structures with javadsa using javadsa using java practicaldsa using java program
TechVidvan Team
TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.