import java.util.Scanner; public class BinarySearch Tree { static class TreeNode { int data; TreeNode left, right; public TreeNode(int data) { this.data = data; left = right = null; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter integers to add to the binary search tree (separated by spaces): "); String[] values = scanner.nextLine().split(" "); TreeNode root = null; for (String value : values) { int int Value = Integer.parseInt(value); root = insert(root, intValue); } System.out.println("Binary Search Tree constructed."); System.out.println("Enter the search value: "); int search Value = scanner.nextInt(); int iterations = search(root, search Value); System.out.println("Found search value in: " + iterations + " iterations"); } private static TreeNode insert(TreeNode root, int data) { if (root == null) { return new TreeNode(data); } if (data < root.data) { root.left = insert(root.left, data); } else if (data > root.data) { root.right = insert(root.right, data); } return root; } private static int search(TreeNode root, int value) { int iterations = 1;
while (root != null) { if (value < root.data) { root = root.left; } else if (value > root.data) { root = root.right; } else { break; } iterations++; } return iterations; } } Output screenshorts: Run BinarySearch Tree x 1 /home/kabangu/ . jdks/openjdk-21. 0. 2/bin/java Enter integers to add to the binary search tre 10 5 12 3 1 13 7 2 4 14 9 8 6 11 IA Binary Search Tree constructed. Enter the search value: 10 Found search value in: 1 iterations Run BinarySearch Tree × 1 /home/kabangu/. jdks/openjdk-21.0.2/bin/java Enter integers to add to the binary search tre 10 5 12 3 1 13 7 2 4 14 9 8 6 11 Binary Search Tree constructed. Run BinarySearch Tree × /home/kabangu/. jdks/openjdk-21.0.2/bin/java - Enter integers to add to the binary search tre 10 5 12 3 1 13 7 2 4 14 9 8 6 11 Binary Search Tree constructed. Enter the search value: 12 Found search value in: 2 iterations
Explanation: D /home/kabangu/. jdks/openjdk-21.0.2/bin/java - jav Enter integers to add to the binary search tree - 10 5 12 3 1 13 7 2 4 14 9 8 6 11 Binary Search Tree constructed. Enter the search value: 9 Found search value in: 4 iterations Process finished with exit code 0 1. TreeNode Class: Represents the structure of a node in the binary search tree. 2. insert Method: Inserts a new value into the binary search tree based on its comparison with the current node. 3. main Method: · Accepts a series of integers from the user and constructs the binary search tree. · Prompts the user for a search value. . Calls the search method to find the value in the tree. 4. search Method: · Performs a binary search on the tree to find the specified value. · Returns the number of iterations required to find the value. Asymptotic Analysis: · The time complexity of the insert operation in the average case is O(log n) for a balanced binary search tree.