class BinarySearchTree { }
class Node { // Search for a value in the BST
int data; public boolean search(int data) {
Node left, right; return searchRec(root, data);
}
public Node(int data) {
this.data = data; // Recursive search function
left = right = null; private boolean searchRec(Node root, int data) {
} if (root == null) {
} return false;
}
private Node root;
if (data == root.data) {
public BinarySearchTree() { return true;
root = null; }
}
if (data < root.data) {
// Insert a node into the BST return searchRec(root.left, data);
public void insert(int data) { }
root = insertRec(root, data);
} return searchRec(root.right, data);
}
// Recursive insert function
private Node insertRec(Node root, int data) { // Main method to test the BinarySearchTree class
if (root == null) { public static void main(String[] args) {
root = new Node(data); BinarySearchTree bst = new BinarySearchTree();
return root;
} // Insert values into the BST
bst.insert(50);
if (data < root.data) { bst.insert(30);
root.left = insertRec(root.left, data); bst.insert(20);
} else if (data > root.data) { bst.insert(40);
root.right = insertRec(root.right, data); bst.insert(70);
} bst.insert(60);
bst.insert(80);
return root;
} // Print the inorder traversal (sorted order)
System.out.println("Inorder traversal:");
// Inorder Traversal (Left, Root, Right) bst.inorder();
public void inorder() {
inorderRec(root); // Search for a value in the BST
} System.out.println("\nSearch 40: " +
bst.search(40));
// Recursive inorder traversal System.out.println("Search 25: " + bst.search(25));
private void inorderRec(Node root) { }
if (root != null) { }
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}