// function iterates through the encoded string // if s[i]=='1' then move to node->right // if s[i]=='0' then move to node->left // if leaf node append the node->data to our output string public string Decode(HuffmanTreeNode root, string encodedStr) { string ans = ""; HuffmanTreeNode curr = root; // loop encoded str for (int i = 0; i < encodedStr.Length; i++) { if (encodedStr[i] == '0') // move to left { curr = curr.Left; } else { curr = curr.Right; // move to right } // reached leaf node if (curr.Left == null && curr.Right == null) { ans += curr.Char; curr = root; } } return(ans); }
public void CreateTree(Dictionary <char, int> charFreqs) { // queue for nodes will be kept in asc order queue = new List <HuffmanTreeNode>(); // Huffman code table will be populated with chars and corresponding binaries counted from Huffman tree CodeTable = new Dictionary <char, string>(); Console.WriteLine("\nHuffman tree:"); foreach (var item in charFreqs) { // create nodes based on chars and frequencies HuffmanTreeNode node = new HuffmanTreeNode(item.Key, item.Value); node.Left = null; node.Right = null; queue.Add(node); } HuffmanTreeNode root = null; // queue handling while (queue.Count > 1) { // 1st node with smallest frequency to extract HuffmanTreeNode x = queue.First(); queue.RemoveAt(0); // 2nd node with smallest frequency y to extract HuffmanTreeNode y = queue.First(); queue.RemoveAt(0); // new node, daddy for the two extracted nodes (sum of the 2 smallest) HuffmanTreeNode f = new HuffmanTreeNode('*', x.Frequency + y.Frequency); // 1st extracted node as left child f.Left = x; // 2nd extracted node as right child f.Right = y; // new node is now root node root = f; // new node to the queue queue.Add(f); // sort queue, has to be in asc order queue.Sort(); // for decoding RootNode = root; } StoreCodes(root, ""); // to dict }
// tree traversal public void StoreCodes(HuffmanTreeNode root, string s) { // base case; if the left and right are null then its a leaf node and store the code s generated by traversing the tree. if (root.Left == null && root.Right == null && Char.IsLetter(root.Char)) { // codetable char if (!CodeTable.ContainsKey(root.Char)) { CodeTable.Add(root.Char, s); } CodeTable[root.Char] = s; Console.WriteLine("\t\t" + root.Char + ":" + s); return; } // if we go to left then add "0" to the code., if we go to the right add "1" to the code. // recursive calls for left and right sub-tree of the generated tree. StoreCodes(root.Left, s + "0"); StoreCodes(root.Right, s + "1"); }