public HuffTreeNode(double inFreq, HuffTreeNode inLeftChild, HuffTreeNode inRightChild) //Constructor used when combining nodes. { freq = inFreq; leftChild = inLeftChild; rightChild = inRightChild; parent = null; }
public HuffTreeNode(double inFreq) //Used when constructing from HuffLeafNode. { freq = inFreq; leftChild = null; rightChild = null; parent = null; }
//Build the Huffman tree. private void buildHuff(List <SymbolFreq> freqTbl, List <HuffLeafNode> leafNodePtrs) { List <HuffTreeNode> huffTree = new List <HuffTreeNode>(); //Contains the nodes that will be combined into the Hoffman tree. HuffTreeNode min1, min2, newNode; HuffLeafNode tempNode; foreach (SymbolFreq SF in freqTbl) //Load the two Lists with leaf nodes. { tempNode = new HuffLeafNode(SF.getFreq(), SF.getSymbol()); huffTree.Add(tempNode); leafNodePtrs.Add(tempNode); } while (huffTree.Count > 1) //Combine nodes until only root node left. { min1 = huffTree[0]; min2 = huffTree[1]; if (huffTree.Count != 2) //if only 2 nodes left, proceed to combine stage. { for (int i = 2; i < huffTree.Count; i++) //Determine smallest in two elements array. { if ((huffTree[i].getFreq() < min1.getFreq()) && (huffTree[i].getFreq() < min2.getFreq())) //Current node frequency smaller than both min1 & min2. { if (min1.getFreq() <= min2.getFreq()) //Find smallest of min1 & min2. If they are equal, replace min1. { min1 = huffTree[i]; } else { min2 = huffTree[i]; } } else if (huffTree[i].getFreq() < min1.getFreq()) //if current node frequency smaller than min1 then set current node as min1. { min1 = huffTree[i]; } else if (huffTree[i].getFreq() < min2.getFreq()) //if current node frequency smaller than min2 then set current node as min2. { min2 = huffTree[i]; } } } newNode = new HuffTreeNode(min1.getFreq() + min2.getFreq(), min1, min2); //create new non-symbol node and update the Huffman tree. min1.setParent(newNode); //Update parent references. min2.setParent(newNode); huffTree.Add(newNode); //Add new node to tree. huffTree.Remove(min1); //Remove combines nodes from tree. huffTree.Remove(min2); } calcHuffCode(leafNodePtrs); //Calculate the huffman code for each leaf node. }
public void setParent(HuffTreeNode inParent) { parent = inParent; }