0
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.

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
  • I think it'll be a lot simpler to build the string going out. Essentially search left sub-tree, if it had the character prepend `0` to the path, else search right sub-tree, prepend `1` to the path. Simpler still is to just traverse the entire tree up front, populate a table via each leaf and then drop the tree, and use the table for the encoding of the message. – 500 - Internal Server Error Nov 03 '22 at 23:46

0 Answers0