public class MLH { // Node class represents a node in the binary search tree
private static class Node { int data; Node left; Node right;
Node(int data) {
this.data = data;
}
}
// root node of the binary search tree
private Node root;
// insert a new node with the given data into the binary search tree
public void insert(int data) { root = insert(root, data); }
// helper method for inserting a new node into the binary search tree
private Node insert(Node node, int data) { if (node == null) { return new Node(data); }
if (data < node.data) {
node.left = insert(node.left, data);
} else if (data > node.data) {
node.right = insert(node.right, data);
}
return node;
}
// search for a node with the given data in the binary search tree
public boolean search(int data) { return search(root, data); }
// helper method for searching for a node with the given data in the binary search tree
private boolean search(Node node, int data) { if (node == null) { return false; }
if (data == node.data) {
return true;
} else if (data < node.data) {
return search(node.left, data);
} else {
return search(node.right, data);
}
}
// main method for testing
public static void main(String[] args) { MLH tree = new MLH();
Scanner input = new Scanner(System.in);
// prompt the user to enter the data for the binary search tree
System.out.println("Enter the data for the binary search tree, separated by spaces: ");
String[] data = input.nextLine().split(" ");
// insert the data into the binary search tree
for (String s : data) {
tree.insert(Integer.parseInt(s));
}
// prompt the user to enter a value to search for
System.out.println("Enter a value to search for in the binary search tree: ");
int searchValue = input.nextInt();
// search for the value in the binary search tree
boolean result = tree.search(searchValue);
if (result) {
System.out.println(searchValue + " was found in the binary search tree.");
} else {
System.out.println(searchValue + " was not found in the binary search tree.");
}
} }


Log in or sign up for Devpost to join the conversation.