public HuffmanTree(string binary) { Queue<char> bitStream = new Queue<char>(); for (int i = 0; i < binary.Length; ++i) { bitStream.Enqueue(binary[i]); } head = buildTreeFromBinary(bitStream); populateSearchStrings(head); }
//Fills the priority queue with the appropriate characters and respective weights private void populateQueue(char[] charset, int[] weights) { topNodes = new PriorityQueue<HuffmanTreeNode>(); for (int i = 0; i < charset.Length; i++) { HuffmanTreeNode currentNode = new HuffmanTreeNode(Char.ToString(charset[i])); topNodes.enqueue(currentNode, weights[i]); } }
private void populateSearchStrings(HuffmanTreeNode currentNode) { string leftCharset = currentNode.Left.Charset; string rightCharset = currentNode.Right.Charset; if (leftCharset == "") { populateSearchStrings(currentNode.Left); leftCharset = currentNode.Left.Charset; } if (rightCharset == "") { populateSearchStrings(currentNode.Right); rightCharset = currentNode.Right.Charset; } currentNode.Charset = leftCharset + rightCharset; }
//Returns whether a node is a leaf node or not private Boolean isLeaf(HuffmanTreeNode node) { return node.Left == null && node.Right == null; }
//constructs a huffman tree from a priority queue of characters private void buildHuffmanTree() { while (topNodes.length() > 1) { int node1Priority = topNodes.lowestPriority(); HuffmanTreeNode node1 = topNodes.dequeueLowest(); int node2Priority = topNodes.lowestPriority(); HuffmanTreeNode node2 = topNodes.dequeueLowest(); HuffmanTreeNode newNode = new HuffmanTreeNode(node1.Charset + node2.Charset, node1, node2); topNodes.enqueue(newNode, node1Priority + node2Priority); } head = topNodes.dequeueHighest(); }
//process for getBinaryRepresentation() //getBinaryRepresentation() is a public interface method which hides the starting parameters of this recursive process from the user private string buildBinaryString(HuffmanTreeNode currentNode) { if (currentNode == null) { return ""; } if (isLeaf(currentNode)) { byte[] bytes = Encoding.ASCII.GetBytes(currentNode.Charset); byte charValue = bytes[0]; string binary = Convert.ToString(charValue, 2).PadLeft(7, '0'); return "1" + binary; } else { return "0" + buildBinaryString(currentNode.Left) + buildBinaryString(currentNode.Right); } }
//constructs leaf node with specified charset public HuffmanTreeNode(string charset) { this.charset = charset; this.left = null; this.right = null; }
//general use constructor public HuffmanTreeNode(string charset, HuffmanTreeNode left, HuffmanTreeNode right) { this.charset = charset; this.left = left; this.right = right; }