Skip to content

Instantly share code, notes, and snippets.

@omi-akif
Created October 5, 2023 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omi-akif/f3df1cf54a59f845242f167eec1153a4 to your computer and use it in GitHub Desktop.
Save omi-akif/f3df1cf54a59f845242f167eec1153a4 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class BinarySearchTreeAssignment {
static class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data) {
this.data = data;
left = null;
right = null;
}
}
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;
}
static int search(TreeNode root, int searchValue) {
int iterations = 0;
TreeNode current = root;
while (current != null) {
iterations++;
if (searchValue == current.data) {
return iterations;
} else if (searchValue < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return -1; // Value not found
}
public static void main(String[] args) {
TreeNode root = null;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter integers to add to the binary search tree (separate with spaces, -1 to stop): ");
int input;
while (true) {
input = scanner.nextInt();
if (input == -1) {
break;
}
root = insert(root, input);
}
System.out.print("Enter the search value: ");
int searchValue = scanner.nextInt();
int iterations = search(root, searchValue);
if (iterations != -1) {
System.out.println("Found search value in " + iterations + " iterations.");
} else {
System.out.println("Search value not found in the binary search tree.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment