132k views
0 votes
Write a Java method named FillTree that can fill a Binary Search Tree using 10 words that are read from the user via the keyboard. The first two words should be your first name and last name. The other 8 words can be anything of your choice. The Binary Search Tree should come from the main method. The main method calls FillTree and pass it a Tree to be filled;

Write a Java method named displayTree. The main method will pass it the Tree created above and the way to display the Tree, such as "postOrder" and "inOrder". Then displayTree will display the Tree as instructed by the main method;

Test the two methods FillTree and displayTree by calling them in the main method. Take a screenshot of the output screen.

User Veor
by
7.6k points

1 Answer

6 votes

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.

User Stephan Keller
by
7.7k points