Java Program Instructions This is a challenging assignment For this assignment y
ID: 3693327 • Letter: J
Question
Java Program
Instructions
This is a challenging assignment
For this assignment you are to develop a program that creates a binary search tree. You are to then read the text file into the binary tree. Finally you are supposed to output the in-order traversal of the binary tree. This should show a sorted list of the 50 state abbreviations in order.
You program will be incorrect if you do not program the binary tree and instead use tree collection.
Use the package name treeStates.
Hints:
You may want to create a Node class to define a tree node
You may want to create a utility class to define how to print tree nodes
You may want to create a BinaryTree class that has a node member
The file they want us to use is named states.txt
The contents of this file is as follows
Explanation / Answer
Node.java
public class Node{
String data;
Node left;
Node right;
public Node(String data){
this.data = data;
left = null;
right = null;
}
}
// BinaryTree.java
public class BinaryTree{
Node root;
public BinaryTree(){
root = null;
}
public BinaryTree(Node n){
root = n;
}
void insert(Node n){
if(root == null){
root = n;
return;
}
Node curr = root;
while(true){
if(curr.data.compareTo(n.data) > 0){
if(curr.left == null) break;
else curr = curr.left;
}
else if(curr.data.compareTo(n.data) < 0){
if(curr.right == null) break;
else curr = curr.right;
}
else if(curr.data.compareTo(n.data) == 0){
return;
}
}
if(curr.data.compareTo(n.data) > 0) curr.left = n;
else if(curr.data.compareTo(n.data) < 0) curr.right = n;
}
}
// utility.java
public class utility{
static void printInorder(Node tree){
if(tree == null) return;
printInorder(tree.left);
System.out.println(tree.data);
printInorder(tree.right);
}
}
// test.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test{
public static void main(String args[]){
BinaryTree tree = new BinaryTree();
Scanner in = null;
try {
in = new Scanner(new File("states.txt"));
} catch (FileNotFoundException e) {
}
while(in.hasNext()){
String string = in.next();
tree.insert(new Node(string));
}
utility.printInorder(tree.root);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.