public HuffmanNode(HuffmanNode h1, HuffmanNode h2) { this.Value = h2.Value + h1.Value; this.ItemCount = h1.ItemCount + h2.ItemCount; this.LeftNode = h2; this.RightNode = h1; }
private void CombineNodeRelations() { if (nodes.Count > 1) { nodes = nodes.OrderBy(x => x.ItemCount).ToList(); HuffmanNode h1 = nodes[0]; h1.BitValue = 1; HuffmanNode h2 = nodes[1]; h2.BitValue = 0; HuffmanNode newNode = new HuffmanNode(h1, h2); nodes.Remove(h1); nodes.Remove(h2); nodes.Add(newNode); CombineNodeRelations(); } }
private string Find(HuffmanNode head, char c) { if (head.Value.Equals(c + "")) { return head.BitValue + ""; } string bitValue = ""; string found = ""; if(head.LeftNode != null) { found = Find(head.LeftNode, c); } if(head.RightNode != null && string.IsNullOrEmpty(found)) { found = Find(head.RightNode, c); } if (!string.IsNullOrEmpty(found)) bitValue = head.BitValue + "" + found; return bitValue; }
private void AddIndividualPiecesAsNodes(Dictionary<string, int> letterCount) { foreach (var item in letterCount) { HuffmanNode hn = new HuffmanNode(); hn.Value = item.Key; hn.ItemCount = item.Value; this.nodes.Add(hn); } }
private string DecompressString(HuffmanNode currentNode, string answer = "") { if (currentNode.Value.Length == 1) { return currentNode.Value; } if (decompressInput[0] == '0') { decompressInput = decompressInput.Skip(1).ToArray(); answer += DecompressString(currentNode.LeftNode); } if (decompressInput.Length > 0 && decompressInput[0] == '1' && string.IsNullOrEmpty(answer)) { decompressInput = decompressInput.Skip(1).ToArray(); answer += DecompressString(currentNode.RightNode); } return answer; }