示例#1
0
        //this will be called recursively, only stops when reaches the leaves
        public void traverseHuffmanTreeForDictionary(HuffmanTreeData theTree, string currentPrefixCode)
        {
            HuffmanDictionary tempData;

            if (theTree.isLeaf) //if this is the leaf, then we add to the list of Dictionary
            {
                tempData = new HuffmanDictionary(theTree.item, currentPrefixCode, theTree.totalCount);
                allPrefixCodes.Add(tempData);
                return;
            }
            traverseHuffmanTreeForDictionary(theTree.left, (currentPrefixCode + "0"));
            traverseHuffmanTreeForDictionary(theTree.right, (currentPrefixCode + "1"));
        }
示例#2
0
        private void createHuffmanTree()
        {
            List <HuffmanTreeData> theTree = new List <HuffmanTreeData>();
            HuffmanTreeData        tempData, tempLeft, tempRight;

            //FIRST put all the items in the allColors to the new list
            foreach (ColorData e in allColors)
            {
                tempData = new HuffmanTreeData(e.colorCode, e.count, null, null, true);
                theTree.Add(tempData);
            }

            if (allColors.Count > 1)
            {
                //make the three
                //extract the two items with the least count and make a new node
                while (theTree.Count > 1)
                {
                    //sort the treeData so that we can extract the least two
                    theTree  = theTree.OrderBy(o => o.totalCount).ToList();
                    tempLeft = theTree.First();  //left of the new tree
                    theTree.RemoveAt(0);
                    tempRight = theTree.First(); //right of the new tree
                    theTree.RemoveAt(0);
                    tempData = new HuffmanTreeData((tempLeft.totalCount + tempRight.totalCount), tempLeft, tempRight, false);
                    theTree.Add(tempData);
                    //MessageBox.Show("Making new node with total count " + (tempLeft.totalCount + tempRight.totalCount) + "\nLeft Total: " + tempLeft.totalCount + "\nLeft Total: " + tempRight.totalCount);
                }

                //traverse the tree which is at the first element of the theTree
                allPrefixCodes = new List <HuffmanDictionary>();
                traverseHuffmanTreeForDictionary(theTree.First(), "");
            }
            else //what if there is only one byte data, then the prefix code for that one item is '0'
            {
                allPrefixCodes = new List <HuffmanDictionary>();
                HuffmanDictionary oneItem;
                tempData = theTree.First();
                oneItem  = new HuffmanDictionary(tempData.item, "0", tempData.totalCount);
                allPrefixCodes.Add(oneItem);
            }
            allPrefixCodes = allPrefixCodes.OrderByDescending(o => o.totalCount).ToList();
            //MessageBox.Show(printAllHuffmanCodes());
        }