private Dictionary<char, string> CreateHuffmanDict(string code,HuffmanTreeNode hTree) { Dictionary<char, string> result = new Dictionary<char, string>(); //如果是叶子节点,那么传入的code就是它的哈夫曼编码 if (hTree.LChild == null && hTree.RChild == null) { result.Add(hTree.Value, code); } else { //否则,约定左边的0,右边的1 var dictL = CreateHuffmanDict(code + "0", hTree.LChild); var dictR = CreateHuffmanDict(code + "1", hTree.RChild); foreach (var item in dictL) { result.Add(item.Key, item.Value); } foreach (var item in dictR) { result.Add(item.Key, item.Value); } } return result; }
private HuffmanTreeNode CreateHuffmanTree(HuffmanTreeNode[] sources) { HuffmanTreeNode topNode = null; HuffmanTreeNode[] nodes = sources; bool bIsNext = true; while (bIsNext) { //先排序 Array.Sort(nodes); //如果只有(或只剩下两个未处理节点),则分别作为左右节点。 //因为已经排序,所以左节点的值小于右节点的值。 if (nodes.Count() == 2) { topNode = new HuffmanTreeNode(); topNode.LChild = nodes[0]; topNode.RChild = nodes[1]; bIsNext = false; } HuffmanTreeNode node1 = sources[sources.Length - 1]; HuffmanTreeNode node2 = sources[sources.Length - 2]; HuffmanTreeNode tmpNode = new HuffmanTreeNode(); tmpNode.Weight = node1.Weight + node2.Weight; tmpNode.LChild = node1; tmpNode.RChild = node2; HuffmanTreeNode[] tmpNds = new HuffmanTreeNode[nodes.Length - 1]; Array.Copy(nodes, 0, tmpNds, 0, nodes.Length - 1); tmpNds[tmpNds.Length - 1] = tmpNode; nodes = tmpNds; } return topNode; }
public Dictionary<char, string> CreateHuffmanDict(HuffmanTreeNode hTree) { return CreateHuffmanDict("", hTree); }