Final answer:
Here the Java program that fills a Binary Search Tree (BST) and displays:
```java
import java.util.Scanner;
class Node {
String data;
Node left, right;
public Node(String item) {
data = item;
left = right = null;
}
}
class BinarySearchTree {
Node root;
public void insert(String data) {
root = insertRec(root, data);
}
private Node insertRec(Node root, String data) {
if (root == null) {
root = new Node(data);
return root;
}
if (data.compareTo(root.data) < 0)
root.left = insertRec(root.left, data);
else if (data.compareTo(root.data) > 0)
root.right = insertRec(root.right, data);
return root;
}
public void displayTree(String order) {
if (order.equals("inOrder"))
inOrder(root);
else if (order.equals("postOrder"))
postOrder(root);
}
private void inOrder(Node root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
private void postOrder(Node root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + " ");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BinarySearchTree tree = new BinarySearchTree();
System.out.println("Enter 10 words:");
for (int i = 0; i < 10; i++) {
String word = scanner.next();
tree.insert(word);
}
System.out.println("Displaying inOrder:");
tree.displayTree("inOrder");
System.out.println("\\Displaying postOrder:");
tree.displayTree("postOrder");
}
}
```
Step-by-step explanation:
The code defines a `BinarySearchTree` class with methods to insert nodes into the tree and display the tree in either in-order or post-order traversal. The `insert` method adds nodes to the tree based on the given word's alphabetical order. The `displayTree` method prints the tree nodes based on the traversal order specified. In the `Main` class, a `Scanner` object reads 10 words from the user, and these words are inserted into the binary search tree using the `insert` method.
Finally, the `displayTree` method is called twice in the `main` method, first to display the tree in in-order traversal and then in post-order traversal. This structure allows users to input data, construct a binary search tree, and visualize it in different traversal orders.
The Java program allows the user to input 10 words, including their first and last name, into a Binary Search Tree using the `fillTree` method. Then, the `displayTree` method showcases the tree in both in-order and post-order traversal in the `main` method.