Beispiel #1
0
        /// <summary>
        /// Builds a Huffman tree out of the given frequencies.
        /// </summary>
        /// <param name="freq">Array of frequencies for a byte at index of byte</param>
        /// <param name="numberOfNodes">Returns number of nodes in Huffman tree</param>
        /// <returns>A fully loaded Huffman tree.</returns>
        private BinaryTreeNode<byte> BuildHuffmanTree(long[] freq, out int numberOfNodes)
        {
            MinPriorityQueue<BinaryTreeNode<byte>> pq = new MinPriorityQueue<BinaryTreeNode<byte>>();

            int count = 0;

            for (int i = 0; i < freq.Length; i++)
            {
                if (freq[i] != 0)
                {
                    BinaryTreeNode<byte> tmp = new BinaryTreeNode<byte>();
                    tmp.RootValue = (byte)i;
                    pq.AddElement(tmp, freq[i]);
                }

            }

            while (pq.Count > 1)
            {
                BinaryTreeNode<byte> root = new BinaryTreeNode<byte>();
                root.IsEmpty = false;
                int weight1 = (int)pq.LowestPriority;

                BinaryTreeNode<byte> child1 = pq.RemoveLowestPriority();
                child1.IsEmpty = false;

                int weight2 = (int)pq.LowestPriority;

                BinaryTreeNode<byte> child2 = pq.RemoveLowestPriority();
                child2.IsEmpty = false;

                root.LeftChild = child1;
                root.RightChild = child2;

                pq.AddElement(root, weight1 + weight2);
                count++;
            }
            numberOfNodes = count + 1;
            BinaryTreeNode<byte> huf = pq.RemoveLowestPriority();

            return huf;
        }