Content
import java.util.Scanner;class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; }}class BST { Node root = null; // Insert Node insert(Node root, int data) { if (root == null) { return new Node(data); } if (data < root.data) { root.left = insert(root.left, data); } else if (data > root.data) { root.right = insert(root.right, data); } return root; } // Search boolean search(Node root, int data) { if (root == null) return false; if (root.data == data) return true; if (data < root.data) return search(root.left, data); else return search(root.right, data); } // Inorder void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + “ “); inorder(root.right); } } // Preorder void preorder(Node root) { if (root != null) { System.out.print(root.data + “ “); preorder(root.left); preorder(root.right); } } // Postorder void postorder(Node root) { if (root != null) { postorder(root.left); postorder(root.right); System.out.print(root.data + “ “); } }}public class BinarySearchTree { public static void main(String[] args) { Scanner sc = new Scanner(System.in); BST tree = new BST(); int choice, data; do { System.out.println(“\n— BINARY SEARCH TREE —”); System.out.println(“1. Insert”); System.out.println(“2. Search”); System.out.println(“3. Inorder”); System.out.println(“4. Preorder”); System.out.println(“5. Postorder”); System.out.println(“6. Exit”); System.out.print(“Enter choice: “); choice = sc.nextInt(); switch (choice) { case 1: System.out.print(“Enter element: “); data = sc.nextInt(); tree.root = tree.insert(tree.root, data); System.out.println(“Element inserted.”); break; case 2: System.out.print(“Enter element to search: “); data = sc.nextInt(); if (tree.search(tree.root, data)) System.out.println(“Element found.”); else System.out.println(“Element not found.”); break; case 3: System.out.print(“Inorder: “); tree.inorder(tree.root); System.out.println(); break; case 4: System.out.print(“Preorder: “); tree.preorder(tree.root); System.out.println(); break; case 5: System.out.print(“Postorder: “); tree.postorder(tree.root); System.out.println(); break; case 6: System.out.println(“Exiting…”); break; default: System.out.println(“Invalid choice.”); } } while (choice != 6); sc.close(); }}