class HuffmanTree implements Comparable<HuffmanTree> { BinaryNode root; // root of tree int totalWeight; // weight of tree static int totalBitsNeeded; // bits needed to represent entire message // (not including code table). public HuffmanTree(Leaf e) { root = new BinaryNode(e, null, null); totalWeight = e.frequency; } public HuffmanTree(HuffmanTree left, HuffmanTree right) { // pre: left and right non-null // post: merge two trees together and add their weights this.totalWeight = left.totalWeight + right.totalWeight; root = new BinaryNode(null, left.root, right.root); } public int compareTo(HuffmanTree other) { return (this.totalWeight - other.totalWeight); } public void print() { // post: print out strings associated with characters in tree totalBitsNeeded = 0; print(this.root, ""); System.out.println("Total bits required for message: " + totalBitsNeeded); } protected static void print(BinaryNode r, String representation) { // post: print out strings associated with chars in tree r, // prefixed by representation if (r.getLeft() != null) { // interior node print(r.getLeft(), representation + "0"); // append a 0 print(r.getRight(), representation + "1"); // append a 1 } else { // leaf; print encoding Leaf e = (Leaf) r.getElement(); System.out.println("Encoding of " + e.ch + " is " + representation + " (frequency was " + e.frequency + ", length of code is " + representation.length() + ")"); totalBitsNeeded += (e.frequency * representation.length()); } } }