示例#1
0
        /// <summary>
        ///     Takes Frequency Value and Establishes Parent/Child relationship with Tree Nodes & Leafs
        /// </summary>
        /// <returns></returns>
        private bool BuildTree()
        {
            //Local Variables
            var iParentIndex = 0;

            var         OptimizedTree = new List <Leaf>(HuffmanTree);
            List <Leaf> WorkingTree;
            Leaf        NewParent;

            //Remove anything with a 0 Frequency Value
            OptimizedTree.RemoveAll(delegate(Leaf leaf) { return(leaf.FrequencyValue == 0); });

            //Order with highest frequency at 'end', lowest at 'beginning'
            OptimizedTree.Sort(delegate(Leaf L1, Leaf L2) { return(L1.FrequencyValue.CompareTo(L2.FrequencyValue)); });

            WorkingTree = new List <Leaf>(OptimizedTree);
            while (WorkingTree.Count > 1)
            {
                //Sort by Frequency
                //Order with highest frequency at 'end', lowest at 'beginning'
                WorkingTree.Sort(delegate(Leaf L1, Leaf L2) { return(L1.FrequencyValue.CompareTo(L2.FrequencyValue)); });

                //Take 'First Two' and join them with a new node
                NewParent = new Leaf {
                    FrequencyValue = WorkingTree[0].FrequencyValue + WorkingTree[1].FrequencyValue, IsNode = true
                };

                HuffmanTree.Add(NewParent);

                //Assign Parent to Left Node
                iParentIndex = HuffmanTree.FindIndex(delegate(Leaf L1) { return(L1.Equals(WorkingTree[0])); });
                HuffmanTree[iParentIndex].Left     = true;
                HuffmanTree[iParentIndex].ParentID = NewParent.ID;

                //Assign Parent to Right Node
                iParentIndex = HuffmanTree.FindIndex(delegate(Leaf L1) { return(L1.Equals(WorkingTree[1])); });
                HuffmanTree[iParentIndex].Right    = true;
                HuffmanTree[iParentIndex].ParentID = NewParent.ID;

                OptimizedTree = new List <Leaf>(HuffmanTree);

                //Remove anything with a 0 Frequency Value
                OptimizedTree.RemoveAll(delegate(Leaf leaf) { return(leaf.FrequencyValue == 0); });

                //Order with highest frequency at 'end', lowest at 'beginning'
                OptimizedTree.Sort(delegate(Leaf L1, Leaf L2) { return(L1.FrequencyValue.CompareTo(L2.FrequencyValue)); });

                WorkingTree = new List <Leaf>(OptimizedTree);

                //Remove anything with a parent
                WorkingTree.RemoveAll(delegate(Leaf leaf) { return(leaf.ParentID != new Guid()); });
            }

            return(true);
        }