package lab10; /** * HuffmanTreeNode * A node in a huffman tree has * a HashMap which associates a {0,1} string with each * T among its children, corresponding to the {left, right} path * you need to follow to get to that child. * a count-- the sum of the counts of all the T at its leaves * a left child, and a right child, both of which are HuffmanTreeNodes * * The huffman algorithm merges the lowest count pair of HuffmanTreeNodes * until there is but one node, the root of the Huffman encoding * For details, see the lectures and lab * * @author rpj * @version 8iv10 */ import java.util.*; public class HuffmanTreeNode implements Comparable> { // instance variables - replace the example below with your own protected HashMap myCodes; protected HuffmanTreeNode left, right; protected Integer count; /** * Constructor for leaf Huffman Tree node * with one datum and its count */ public HuffmanTreeNode(T data, Integer count) { myCodes = new HashMap(); myCodes.put(data, ""); // don't need any huffman code for a leaf this.count = count; left = null; right = null; } /** * Constructor used to merge two Huffman trees into one */ public HuffmanTreeNode(HuffmanTreeNode one, HuffmanTreeNode two) { left = one; right = two; count = one.getCount() + two.getCount(); myCodes = new HashMap(); for (T lKey : one.getKeys()) myCodes.put(lKey, "0"+one.lookup(lKey)); // codes for items in the left child will begin with 0 for (T rKey : two.getKeys()) myCodes.put(rKey, "1"+two.lookup(rKey)); // codes for items in the right child will begin with 1 } /** * get the frequency count of this node */ public Integer getCount() { return count; } /** * get all the keys present in my HashMap */ public Set getKeys() { return myCodes.keySet(); } /** * get the Huffman string associated with T target from this node down */ public String lookup(T target) { return myCodes.get(target); } /** * how do I compare to another? */ public int compareTo(HuffmanTreeNode other) { return count.compareTo(other.getCount()); } }