Traversing helper method for a Huffman tree

3.2k views Asked by At

In this programming assignment, we must make a helper method called traverse that is called by getCodes(). It is a recursive method to traverse the Huffman Tree and add a Code record to the ArrayList for each leaf node in the tree. Any help is much appreciated I've been stuck on this for 3 hours now.

/* This method returns an ArrayList of the codes in the Huffman Tree.
 * The Code class has a character and its corresponding encoding.  In the
 * tree, left edges are designated as 0 and right edges as 1.
 * 
 * DO NOT CHANGE THIS METHOD, but you need to write the traverse method.
 */
public ArrayList<Code> getCodes() {
        ArrayList<Code> code = new ArrayList<Code>();
        if (root == null) return null;
        traverse(code, root.left, "0");
        traverse(code, root.right, "1");
        return code;
}

/* Recursive method to traverse the Huffman tree, and for each leaf node,
 * add a Code record to the ArrayList.
 */
private void traverse(ArrayList<Code> code, BinaryTreeNode<Letter> node,
                     String prefix) {
        // TODO:  Fill in this method
    // base case
    if(node==null) return;
    //else traverse the left then right
    if(node!=null){traverse(code,node.left, prefix);}
    if(node!=null){traverse(code,node.right,prefix);}
    code.add(node.getElement());
}
1

There are 1 answers

0
Fellowstudent On
traverse(code, node.getLeft(), prefix + "0");

traverse(code, node.getRight(), prefix + "1");

code.add(Code(node.getElement().getLetter(), prefix));

Edit: You never updated prefix and you weren't adding the correct object to the arraylist. I know this is your homework btw.