2

I need to make a String Representation of a Huffman Tree. It uses pre-order traversal and the output will produce a String using 'I' (for interior node) and 'L' (for leaf node) followed by the leaf node character.

public static String getTreeString(final BinaryNodeInterface<Character> root)
{               
            String treeString="";
            if(root == null)
                return "";
            if(root.isLeaf())
                treeString = treeString + "L" + root.getData();
            else
            {
                treeString = treeString + "I";
                getTreeString(root.getLeftChild());
                getTreeString(root.getRightChild());
            }

            return treeString;

}

When I debug the program it goes through and creates the right String but it cannot be saved due to the String treeString=""; at the beginning of the method.

Desired output: IIILaILbILcLdLe

My output: I

Also, I am not allowed to use any global/instance variables or any Java pre-defined classes.

Edward
  • 6,964
  • 2
  • 29
  • 55

1 Answers1

3

The following code:

getTreeString(root.getLeftChild());
getTreeString(root.getRightChild());

should be

treeString += getTreeString(root.getLeftChild());
treeString += getTreeString(root.getRightChild());

You do not append your results to treeString.

Andy T
  • 136
  • 11