Esempio n. 1
0
 //Recursive method to build codes, starting at top node
 public Dictionary <char, string> getEncodeMap(HuffmanNode top, string result)
 {
     if (top.Left != null)
     {
         getEncodeMap(top.Left, result + "0");
     }
     if (top.Right != null)
     {
         getEncodeMap(top.Right, result + "1");
     }
     //We've reached a leaf
     if (top.Left == null)
     {
         if (!encodeData.ContainsKey(top.Symbol))
         {
             encodeData.Add(top.Symbol, result);
         }
     }
     return(encodeData);
 }
Esempio n. 2
0
        public void Build(Vector <char> vector)
        {
            //Get our frequencies
            var dict = getFrequencyTable(vector).OrderBy(values => values.Value);
            List <HuffmanNode> nodes = new List <HuffmanNode>();

            //Build nodes based on those frequencies
            foreach (KeyValuePair <char, int> nodeData in dict)
            {
                HuffmanNode node = new HuffmanNode();
                node.Symbol = nodeData.Key;
                node.Value  = nodeData.Value;
                nodes.Add(node);
            }
            while (nodes.Count > 1)
            {
                //Get lowest vals
                HuffmanNode smallest     = nodes[0];
                HuffmanNode nextSmallest = nodes[1];
                //Create parent
                HuffmanNode parent = new HuffmanNode();
                //Set value and children
                parent.Value = smallest.Value + nextSmallest.Value;
                parent.Left  = smallest;
                parent.Right = nextSmallest;
                //Add parent to top of queue
                nodes.Add(parent);

                //Remove values from list
                nodes.Remove(smallest);
                nodes.Remove(nextSmallest);
                //Reorder list to maintain integrity
                nodes = nodes.OrderBy(values => values.Value).ToList();
            }
            Root = nodes[0];            //This is top of tree
        }