Created
October 5, 2023 02:54
-
-
Save omi-akif/f3df1cf54a59f845242f167eec1153a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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