Question

Please create a class in Java that completes the following conditions

Using your Morse code tree from last assignment, complete the following additional tasks: Write a program that will repeatedl

Example output: (note: you should not italicize your output, and elipsis are used only to indicate that more is expected) You

MorseTree.java

/* This program will read in letters followed by their morse code
* and insert them properly in a tree based on the amount of symbols
* it has and whether they are left or right descendent. Finally
* it prints a few certain nodes.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class MorseTree {

   public static void main(String[] args) throws FileNotFoundException {

       // Scanner object for text file
       Scanner file = new Scanner(new File("morsecode.txt"));

       // Creates root node for tree
       TreeNode<String> root = new TreeNode<String>();

       while (file.hasNext()) {
           // Stores next line of file as a string
           String line = file.nextLine();

           // scans the line for the element and its insertion path
           Scanner code = new Scanner(line);

           // temp and current nodes used for insertion to tree
           TreeNode<String> temp = new TreeNode<String>(code.next());
           TreeNode<String> current = root;

           while (code.hasNext()) { // PRE: String is passed in
               if (code.next().equals("o")) {
                   if (current.getLeft() == null)
                       current.setLeft(temp);
                   else
                       current = current.getLeft();
               } else {
                   if (current.getRight() == null)
                       current.setRight(temp);
                   else
                       current = current.getRight();
                   // POST: symbol is inserted to tree based on if its left or right descendent
               }
           }
           code.close();
       }
       file.close();

       // prints z ( - - o o)
       System.out.println(root.getRight().getRight().getLeft().getLeft().getElement());

       // prints q (- - o -)
       System.out.println(root.getRight().getRight().getLeft().getRight().getElement());

       // prints r (o - o)
       System.out.println(root.getLeft().getRight().getLeft().getElement());
   }
}

TreeNode.java

public class TreeNode<T> {
   private T element;
   private TreeNode<T> left;
   private TreeNode<T> right;

   public TreeNode(T element) {
       this.element = element;
   }

   public TreeNode() {
       this.element = null;
   }

   public T getElement() {
       return element;
   }

   public TreeNode<T> getLeft() {
       return left;
   }

   public TreeNode<T> getRight() {
       return right;
   }

   public boolean isLeaf() {
       return this.getLeft() == null && this.getRight() == null;
   }

   public void setLeft(TreeNode<T> t) {
       left = t;
   }

   public void setRight(TreeNode<T> t) {
       right = t;
   }

   public void preorder(TreeNode<T> node) {
       if (node == null) {
           return;
       }
       System.out.println(node.getElement());
       preorder(node.getLeft());
       preorder(node.getRight());
   }

   public void postorder(TreeNode<T> node) {
       if (node == null) {
           return;
       }
       postorder(node.getLeft());
       postorder(node.getRight());
       System.out.println(node.getElement());
   }

   public int height() {
       if (this.isLeaf()) {
           return 0;
       } else if (this.getLeft() != null && this.getRight() == null) {
           return this.getLeft().height() + 1;
       } else if (this.getLeft() == null && this.getRight() != null) {
           return this.getRight().height() + 1;
       } else {
           return Math.max(this.getLeft().height(), this.getRight().height()) + 1;
       }
   }

   public void insert(T element) {
       TreeNode<T> insertTarget = new TreeNode<T>(element);
//       while(!temp.isLeaf()) {
//           temp = temp.getLeft();
//       }
//       temp.setLeft(insertTarget);

//       if (this.isLeaf()) {
//           this.setLeft(insertTarget);
//       }
//       else if (this.getLeft() == null) {
//           this.setLeft(insertTarget);
//       }
//       else if (this.getRight() == null){
//           this.setRight(insertTarget);
//       }
//       else {
//           this.getLeft().insert(element);
//       }

//       if (height() == 0) {
//           return;
//       }
       if (height() == 0) {
           this.setLeft(insertTarget);
       } else {
           if (this.getLeft() == null) {
               this.setLeft(insertTarget);
           } else if (this.getRight() == null) {
               this.setRight(insertTarget);
           } else {
               if (this.getLeft().height() <= this.getRight().height()) {
                   this.getLeft().insert(element);
               } else if (this.getLeft().height() > this.getRight().height()) {
                   this.getRight().insert(element);
               }
           }
       }
   }

   public void insertLeft(T element) {
       if (this.getLeft() == null) {
           this.setLeft(new TreeNode<T>(element));
       } else {
           System.out.println("Tried to insert a node overwriting an existing node on the left!");
       }
   }

   public void insertRight(T element) {
       if (this.getRight() == null) {
           this.setRight(new TreeNode<T>(element));
       } else {
           System.out.println("Tried to insert a node overwriting an existing node on the right!");
       }}}

morsecode.txt

e o
t -
i o o
a o -
n - o
m - -
s o o o
u o o -
r o - o
w o - -
d - o o
k - o -
g - - o
o - - -
h o o o o
v o o o -
f o o - o
l o - o o
p o - - o
j o - - -
b - o o o
x - o o -
c - o - o
y - o - -
z - - o o
q - - o -

Please create the test class the completes the bulleted requests in the beginning.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.File;

import java.io.FileNotFoundException;

import java.util.*;

public class MorseTree {

private TreeNode root;

//Constructor for the morseTree, Opens file and reads the morse translation

public MorseTree() {

//first, open data.txt, add each line to the tree

Scanner fin;

try {

File file = new File("data.txt");

fin = new Scanner(file);

while(fin.hasNextLine()){

String temp = fin.nextLine();

add(temp.substring(2), temp.charAt(0));

}

} catch (FileNotFoundException e) {

System.out.println("File not found!");

e.printStackTrace();

}

}

// add sends to insertInSubtree

public void add(String morseStr, char letter) {

root = insertInSubtree(morseStr, letter, root);

}

// Inserts the character to the appropriate location within the tree

private TreeNode insertInSubtree(String morseStr, char letter, TreeNode subtree) {

if(subtree == null)

return insertInSubtree(morseStr, letter, new TreeNode());

if(morseStr.length() == 1){

subtree.data = letter;

return subtree;

}

else if(morseStr.charAt(0)=='.')

subtree.setRight(insertInSubtree(morseStr.substring(1), letter, subtree.right));

else if(morseStr.charAt(0)=='-')

subtree.setLeft(insertInSubtree(morseStr.substring(1), letter, subtree.left));

return subtree;

}

public Character translate(String morseStr) {

return findInSubtree(morseStr, root);

}

private Character findInSubtree(String morseStr, TreeNode subtree) {

if(subtree == null)

return null;

if(morseStr.length() == 0)

return (Character) subtree.data;

else if(morseStr.charAt(0)=='.')

return findInSubtree(morseStr.substring(1), subtree.right);

else if(morseStr.charAt(0)=='-')

return findInSubtree(morseStr.substring(1), subtree.left);

return null;

}

// translates a string by concantenating a string of morseStrings

public String translateString(String tokens) {

String retVal = "";

Scanner input = new Scanner(tokens);

while(input.hasNext())

retVal += findInSubtree(input.next(), this.root)+ " ";

input.close();

return retVal;

}

/*

public String toMorseCode(Character c) {

.

//walk the tree looking for the TreeNode with the char c in it

//preorder walk?

//inorder walk?

//postorder walk?

return new String("You wish.");

}

public String toString() {

return inorderWalk();

}

private String inorderWalk() {

return new String("Another wish.");

}

*/

public static void main(String[] args) {

MorseTree mt = new MorseTree(); //builds our tree using data from a file

System.out.println();

System.out.println(mt.translateString(".- -... -.-. -.. .")); //prints out A B C D E

System.out.println(mt.translateString("..-. --. .... .. .---")); //prints out F G H I J

System.out.println(mt.translateString("-.- .-.. -- -. ---")); //prints out K L M N O

System.out.println(mt.translateString(".--. --.- .-. ... -")); //prints out P Q R S T

System.out.println(mt.translateString("..- ...- .-- -..- -.--")); //prints out U V W X Y

System.out.println(mt.translateString("--.. ----- .---- ..--- ...--")); //prints out Z 0 1 2 3

System.out.println(mt.translateString("....- ..... -.... --... ---..")); //prints out 4 5 6 7 8

System.out.println(mt.translate("----.")); //prints out 9

System.out.println(mt.translate(".......-")); //prints out null

System.out.println(mt.translateString("... --- ...")); //SOS

//System.out.println(mt.toMorseCode('S')); //find where we are in the tree, remember path to root

}

private class TreeNode {

Object data;

TreeNode right;

TreeNode left;

public TreeNode() {

this.data = null;

this.right = null;

this.left = null;

}

public TreeNode(Object data, TreeNode leftNode, TreeNode rightNode){

this.data = data;

this.left = leftNode;

this.right = rightNode;

}

public void setRight(TreeNode rightNode) {

this.right = rightNode;

}

public void setLeft(TreeNode leftNode) {

this.left = leftNode;

}

}

}

-----------------------------------------------------------------------------------------------------

import java.io.*;

import java.util.*;

public class CharTree {

private static class TreeNode {

private char data;

private TreeNode leftLink;

private TreeNode rightLink;

public TreeNode(char newData, TreeNode newLeftLink, TreeNode newRightLink) {

this.data = newData;

this.leftLink = newLeftLink;

this.rightLink = newRightLink;

}

}

// The first node of the tree, called root

private TreeNode root;

// Default constructor to build the CharTree

public CharTree( ) {

root = null;

}

// Utility methods for CharTree:

public void add(char item) {

root = insertInSubtree(item, root);

}

public boolean contains(char item) {

return isInSubtree(item, root);

}

public void showElements( ) {

showElementsInSubtree(root);

}

private static TreeNode insertInSubtree(char item, TreeNode subTreeRoot) {

if (subTreeRoot == null)

return new TreeNode(item, null, null);

else if (item < subTreeRoot.data) {

subTreeRoot.leftLink = insertInSubtree(item, subTreeRoot.leftLink);

return subTreeRoot;

}

else { //item >= subTreeRoot.data

subTreeRoot.rightLink = insertInSubtree(item, subTreeRoot.rightLink);

return subTreeRoot;

}

}

private static boolean isInSubtree(char item, TreeNode subTreeRoot) {

// base case: is subTreeRoot null? then return false

if(subTreeRoot == null)

return false;

else if(subTreeRoot.data == item)

return true;

else if(item < subTreeRoot.data)

return isInSubtree(item, subTreeRoot.leftLink);

else if(item >= subTreeRoot.data)

return isInSubtree(item, subTreeRoot.rightLink);

return false; // Failsafe

}

private static void showElementsInSubtree(TreeNode subTreeRoot) { //Uses inorder traversal.

if (subTreeRoot != null) {

showElementsInSubtree(subTreeRoot.leftLink);

System.out.print(subTreeRoot.data + " ");

showElementsInSubtree(subTreeRoot.rightLink);

} //else do nothing. Empty tree has nothing to display.

}

public static void main(String[] args) {

CharTree tree = new CharTree();

tree.add('c');

tree.add('a');

tree.add('t');

tree.add('s');

showElementsInSubtree(tree.root);

System.out.println();

System.out.println("Is 'a' in the subtree? "+isInSubtree('a', tree.root));

System.out.println("Is 't' in the subtree? "+isInSubtree('t', tree.root));

System.out.println("Is 'b' in the subtree? "+isInSubtree('b', tree.root));

}

}

MorseTree [-/ldeaProjects/MorseTree] - ../sro/MorseTree.java [MorseTree] G MorseTree MorseTree src Main O Project- V MorseTre

Note:---If you have any doubts then commebt below

Add a comment
Know the answer?
Add Answer to:
Please create a class in Java that completes the following conditions MorseTree.java /* This program will...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • Please help me with me. I did the first part to write the operations but in...

    Please help me with me. I did the first part to write the operations but in the driver its shows me errors, can't fix it. Help me. Need help with this to run the application. /** * BinaryTreeNode represents a node in a binary tree with a left and * right child. * * @author Java Foundations * @version 4.0 */ public class BinaryTreeNode { protected T element; protected BinaryTreeNode left, right; /** * Creates a new tree node with...

  • write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the word...

    write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the words in order (based on ASCII/UNICODE order) on the screen (or to output text file). Note that you may need to make some changes to BST.java. Sample test: ----jGRASP exec: java -ea removeDuplicates Original Text: a B 2 n w C q K l 0...

  • Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException;...

    Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BSTTreeNode{    BSTTreeNode left, right;    String data; public BSTTreeNode(){    left = null;    right = null;    data = null; } public BSTTreeNode(String n){    left = null;    right = null;    data = n; } public void setLeft(BSTTreeNode n){    left = n; } public void setRight(BSTTreeNode n){   ...

  • Can you take a look at my code that why the maxDepth function is not working?...

    Can you take a look at my code that why the maxDepth function is not working? public class BinaryTree {          class Node{        int key;        Node left,right;               public Node(int item) {            key = item;            left = right = null;        }    }       Node root;       public void BinaryTree(){        root = null;    }           void...

  • i need help to modify this Tree class to include a method leavesCount that returns the...

    i need help to modify this Tree class to include a method leavesCount that returns the number of leaves in a binary tree. (NOTE: Complete leavesCount and leavesCountHelper methods in the Tree class). I already have the test class. java class TreeNode< T extends Comparable< T > > { TreeNode< T > leftNode; T data; TreeNode< T > rightNode; public TreeNode( T nodeData ) { data = nodeData; leftNode = rightNode = null; } public void insert( T insertValue )...

  • please make a pretty JAVA GUI for this code this is RED BLACK TREE and i...

    please make a pretty JAVA GUI for this code this is RED BLACK TREE and i Finished code already jus need a JAVA GUI for this code ... if poosible make it pretty to look thanks and please make own GUI code base on my code thanks ex: (GUI only have to show RBTree) ---------------------------------------- RBTree.java import java.util.Stack; public class RBTree{    private Node current;    private Node parent;    private Node grandparent;    private Node header;    private Node...

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • Question B1 You are given the following Java classes: public class Queue { private static class...

    Question B1 You are given the following Java classes: public class Queue { private static class Node { Object object; Node next; Node () { object = null; next = null; } Node (Object object, Node next) { this.object = object; this.next = next; private Node header; private int size = 0; // size shows the no of elements in queue public Object dequeue () { if (size == 0 ) { return null; else { Object remove_object = header.object;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT