public String searchTreeNode(Character target, TreeNode current, String result) {
Character left = current.getLeft().getData().getCharacter();
Character right = current.getRight().getData().getCharacter();
//Both children are characters
if(left != null && right != null){
//found at right
if(right == target){
result += "1";
}
//found at left
else if (left == target){
result += "0";
}
}
//left is a character and right is a null
else if(left != null && right == null){
//found at left
if(left == target){
result += "0";
}
//move to right node
else{
result = searchTreeNode(target, current.getRight(), "1" + result);
}
}
//right is a character and left is a null
else if(right != null && left == null){
//found at right
if(right == target){
result += "1";
}
//move to left node
else{
result = searchTreeNode(target, current.getLeft(), "0" + result);
}
}
//if both children are null
else if (right == null && left == null){
result = searchTreeNode(target, current.getLeft(), result) + searchTreeNode(target, current.getRight(), result);
}
else{
result = "";
}
return result;
}
In a Huffman root tree it is easy to know which direction to go if one is null and another is a character since you either find the character, or go down the null child. However if both children are null, I cannot figure out how to null the side that doesn't find the child since I traverse both. Is there a way to null the side that doesn't result in finding the target?
When I traversed both sides, I would add up both sides that would recursively go through the function until it found the target or ended up null within the else statement. However since it has already "traversed" with recursion I cannot null the already added bit strings. So instead of only printing the path towards the target only it print both sides.