Final answer:
To fill a Binary Search Tree in Java, you can write a method called FillTree that takes input from the user and populates the tree. The first two words should be the user's first and last name. The other 8 words can be of the user's choice.
Step-by-step explanation:
In order to fill a Binary Search Tree using Java, you can write a method called FillTree. This method takes input from the user via the keyboard and adds 10 words to the tree. The first two words should be the user's first name and last name. The other 8 words can be of the user's choice.
Here's an example implementation of the FillTree method:
import java.util.Scanner;
class Node {
String data;
Node left, right;
public Node(String item) {
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
void FillTree(Node node, int numWords) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first name:");
node.data = sc.nextLine();
System.out.println("Enter the last name:");
node.data = sc.nextLine();
for (int i = 0; i < numWords - 2; i++) {
System.out.println("Enter a word:");
String word = sc.nextLine();
insert(node, word);
}
}
void insert(Node node, String data) {
if (data.compareTo(node.data) < 0) {
if (node.left == null) {
node.left = new Node(data);
} else {
insert(node.left, data);
}
} else if (data.compareTo(node.data) > 0) {
if (node.right == null) {
node.right = new Node(data);
} else {
insert(node.right, data);
}
}
}
}
You can then create a Tree object in your main method, call the FillTree method to fill the tree, and then call the displayTree method to display the tree in the desired order. The displayTree method can use various tree traversal algorithms like inorder, preorder, or postorder to display the tree.