Binary tree insert()
I am trying to fill a binary tree with letters which will then be used to encode a Morse code sequence but I am stuck on my insert() method its adding a letter twice or more.
If the code has a '.' it will go left
If the code has '-' it will go rightAnd then I am trying to traverse it, but my output is showing me lots of the same letter
Here is my insert()
:
private void insert(BinaryNode localRoot, BinaryNode node){
if (localRoot == null) { //Replace empty tree with new tree with the item at the root.
localRoot = node;
return;
}
String result = node.getData().toString();//getting Item from BinaryNode.java
//looping over morse code
for(int cnt = 0;cnt<result.length();cnt++){
if(result.cha开发者_C百科rAt(cnt)=='.')
{
if (localRoot.getLeftSubtree() == null){
localRoot.setLeftSubtree(node);}
}
else if(result.charAt(cnt)=='-'){
if (localRoot.getRightSubtree() == null)
localRoot.setRightSubtree(node);
}
}
}
Your insert method is looping over the whole node string. When it finds a '.' it adds to the left. When it finds a '-' it adds to the right. If your node string has both '.' and '-' in it, it will be added to the left and the right (if the left and right were null to start with). I'm not sure what you are trying to do, but it's possible you should only be checking the first letter in your node string.
Does it have to be a tree? Why not use a hashmap?
Your insert
does the following:
If localroot is null, do nothing (well you set two local variables to be the same, but overall that is a no-op) If your localroot is not null, you set its left subtree to node, for every '.' you find and the right subtree for every '-' you find.
I don't know what your initial "localroot" is, but assuming its an (non null) node representing the empty morse-string, after inserting "A", i.e., ".-", your root will have two children "A" and "A" (the same node object), and will then be replaced by "B", then by "C", "D" and then by "E", which will only set the left subtree...
精彩评论