/** ****************************************************************************** * HOMEWORK 15-211 COMPRESSION ****************************************************************************** * * Represents a node in the Huffman tree. * * *****************************************************************************/ /***************************************************************************** There is no need to modify this file. *****************************************************************************/ public class HuffmanNode implements Comparable { private byte value; private int freq; private HuffmanNode left, right, parent; /** * Creates a leaf node with a given frequency * * @throws IllegalArgumentException * if freq is negative */ public HuffmanNode (byte value, int freq) { if (freq < 0) throw new IllegalArgumentException ("frequence needs to be non-negative"); this.value = value; this.freq = freq; } /** * Creates an internal node with the given childern. * * @param l * The left child * @param r * The right child * @throws IllegalArgumentException * If either l or r is null. */ public HuffmanNode (HuffmanNode l, HuffmanNode r) { if (l == null || r == null) throw new IllegalArgumentException ("Trying to create an internal node with a null child"); left = l; right = r; left.parent = right.parent = this; this.freq = l.getFreq () + r.getFreq (); } /** * Compares two nodes by their frequences */ public int compareTo(HuffmanNode node) { return freq - node.freq; } /** * Checks if this is a leaf node */ public boolean isLeaf () { return left == null && right == null; } /** Checks if this is the root of the Huffman tree. */ public boolean isRoot () { return parent == null; } /** Gets the frequency of this node. */ public int getFreq () { return freq; } /** * Gets the value of this node, or null if this is an internal node */ public byte getValue () { return value; } /** * Gets the parent of this node, or null if this is the root of the Huffman * tree. */ public HuffmanNode getParent () { return parent; } /** * Gets the left child of this node, or null if this is a leaf. */ public HuffmanNode getLeft () { return left; } /** * Gets the right child of this node, or null if this is a leaf. */ public HuffmanNode getRight () { return right; } }