/**
A Morse code decoder based on a binary tree
*/
public class Decoder {
private BinaryTreeNode root;
public Decoder() {
root = new BinaryTreeNode(""); // root node has no information
//
// there must be a better way to do this...
//
root.setLeft(new BinaryTreeNode("e"));
root.setRight(new BinaryTreeNode("t"));
root.getLeft().setLeft(new BinaryTreeNode("i"));
root.getLeft().setRight(new BinaryTreeNode("a"));
root.getRight().setLeft(new BinaryTreeNode("n"));
root.getRight().setRight(new BinaryTreeNode("m"));
//added by me
root.getLeft().getLeft().setLeft(new BinaryTreeNode("t"));
root.getLeft().getLeft().setRight(new BinaryTreeNode("n"));
root.getLeft().getRight().setLeft(new BinaryTreeNode("l"));
root.getLeft().getRight().setRight(new BinaryTreeNode("w"));
}
//
// An iterative version of the Morse code decoder
//
public String decode(String m) {
BinaryTreeNode ptr = root; // start at root of tree
String str="?"; // decoded character
// scan through the Morse string
for (int i=0;i<m.length();i++)
{
if (ptr==null)
str = "Yipes! Can't decode Morse string!";
else
if (m.charAt(i)=='.')
ptr=ptr.getLeft();
else
if (m.charAt(i)=='-')
ptr=ptr.getRight();
}
if (ptr!=null)
str = (String)ptr.getValue();
return str;
}
//
// A Recursive version of the decoder
//
private String decodeR(BinaryTreeNode n, String m) {
String str="?";
if (n!=null) {
if (m.length()==0)
str = (String)n.getValue();
else
if (m.charAt(0)=='.')
str = decodeR(n.getLeft() , m.substring(1)) ;
else
if (m.charAt(0)=='-')
str = decodeR(n.getRight() , m.substring(1));
}
return str;
}
//
// public wrapper function to hide decodeR()
//
public String decode2(String m) {
return decodeR(root, m);
}
}