示例#1
0
        /// <summary>
        /// Creat Huffman tree
        /// </summary>
        /// <param name="frequencies">Dictionary of frequencies</param>
        private void HuffmanTree(IEnumerable <KeyValuePair <char, int> > frequencies)
        {
            HuffmanQueue <HuffmanNode> priorityQueue = new HuffmanQueue <HuffmanNode>();

            foreach (KeyValuePair <char, int> item in frequencies)
            {
                priorityQueue.Queue(new HuffmanNode {
                    value = item.Key, probability = GetProbability(item.Value)
                }, GetProbability(item.Value));
            }
            while (priorityQueue.Count > 1)
            {
                HuffmanNode n1      = priorityQueue.Dequeue();
                HuffmanNode n2      = priorityQueue.Dequeue();
                HuffmanNode newNode = new HuffmanNode {
                    left = n1, right = n2, probability = SumOfProbabilities(n1.probability, n2.probability)
                };
                n1.parent = newNode;
                n2.parent = newNode;
                priorityQueue.Queue(newNode, newNode.probability);
            }
            root = priorityQueue.Dequeue();
        }