Beispiel #1
0
        private static HuffmanTreeNode CreateAndSortTree(List <HuffmanTreeNode> frequencies)
        {
            //Sort and create the tree
            while (frequencies.Count > 1)
            {
                // Order frequencies ascending
                frequencies = frequencies.OrderBy(n => n.Frequency).ToList();

                // Create new tree node with the 2 elements of least frequency
                var leastFrequencyNode = new HuffmanTreeNode(frequencies[0].Frequency + frequencies[1].Frequency)
                {
                    Children = frequencies.Take(2).ToArray()
                };

                // Remove those least frequency elements and append new tree node to frequencies
                frequencies = frequencies.Skip(2).Concat(new[] { leastFrequencyNode }).ToList();

                // This ultimately results in a tree like structure where the most frequent elements are closer to the root;
                // while less frequent elements are farther from the root

                // Example:
                // (F:4)
                //   (F:3)
                //     (F:1)
                //     (F:2)
                //   (F:1)
            }

            return(frequencies.First());
        }
Beispiel #2
0
        private void WriteTreeNode(BitWriter bw, HuffmanTreeNode huffmanTreeNode, int bitCount)
        {
            if (huffmanTreeNode.IsLeaf)
            {
                bw.WriteBit(0);
                bw.WriteBits(huffmanTreeNode.Code, bitCount);
                return;
            }

            bw.WriteBit(1);
            WriteTreeNode(bw, huffmanTreeNode.Children[0], bitCount);
            WriteTreeNode(bw, huffmanTreeNode.Children[1], bitCount);
        }