Esempio n. 1
0
        public HuffmanTree(Dictionary <int, int> counts) //O(N)
        {
            PriorityQueue <HuffmanNode> priorityQueue = new PriorityQueue <HuffmanNode>();

            foreach (KeyValuePair <int, int> kvp in counts)
            {
                HuffmanNode N = new HuffmanNode();
                N.Value = kvp.Key;
                N.Count = kvp.Value;
                priorityQueue.Enqueue(N, kvp.Value);
            }

            while (priorityQueue.Count > 1)
            {
                HuffmanNode n1 = priorityQueue.Dequeue();
                HuffmanNode n2 = priorityQueue.Dequeue();
                HuffmanNode n3 = new HuffmanNode();
                n3.Left = n2; n3.Right = n1; n3.Count = n1.Count + n2.Count;
                priorityQueue.Enqueue(n3, n3.Count);
            }

            root = priorityQueue.Dequeue();
        }