Given the alphabet and a morse code value for each letter...
a._
b_...
c_._.
d_.. //file to be read in
e.
f.._.
I'm attempting to create a tree, finding the position for a letter in the tree by scanning the code, and branching left for a dot and branching right for a dash.
I've created a node class with the typical numberNode left and numberNode right variables along with morseCode and letter. Here's my function.
aList is an arraylist of created nodes read in from a file. rootNode is the root of the tree, having no set letter or morsecode.
public static void createTree(ArrayList<numberNode> aList, numberNode rootNode)
{
for (numberNode n : aList) //for each numberNode in aList
{
int lengthOfCode = n.getmorseCode().length()-1; //get the length of the morsecode
numberNode currentNode = rootNode; //sets currentNode to the rootNode at first
for (int i=0; i<lengthOfCode; i++)
{
char c = n.getmorseCode().charAt(i); //for each char in morsecode until it gets to the end
if (c == '.')
{
if (currentNode.getleft() = null) //if currentnode left is null
{
numberNode newLeftNode = new numberNode(); //create new node
currentNode.setleft(newLeftNode); //set current node left to the new node
if (i == lengthOfCode)
{
currentNode.setleft(n); //if end of morse code, set the current node left's to n
}
else
{
currentNode = newLeftNode; //else change current node to the newly created leftnode
}
}
else //if current node left is not null
{
if (i == lengthOfCode)
{
currentNode.setleft(n); //if at end of morse code
}
currentNode = currentNode.getleft(); //if not at end set current node to current node's left
}
}
if (c == '_')
{
if (currentNode.right() =null)
{
numberNode newRightNode = new numberNode();
currentNode.setleft(newRightNode);
if (i == lengthOfCode)
{
currentNode.setright(n);
}
else
{
currentNode = newRightNode;
}
}
else
{
if (i == lengthOfCode)
{
currentNode.setright(n);
}
currentNode = currentNode.getright();
}
}
}
}
}
Couple questions I have...
Is my algorithm at least correct?
Is there an alternate way of doing this without it being so ugly?
If you need to see any more of my code please don't hesitate to ask. Thanks for your time, I truly appreciate it!
EDIT: Currently runs, but when I try to print out the output using...
for (numberNode n : nodeArray)
{
System.out.println(n.getletter());
System.out.println(n.getleft().getletter().toString()); //error here
System.out.println(n.getright().getletter());
System.out.println("");
}
I get an error where indicated,Any ideas on what's going wrong?