public static HuffmanTree <T> BuildTree(List <HuffmanEntry <T> > items) { var nodes = items.Select(a => new HuffmanBinaryNode <T>() { Weight = a.Frequency, Value = a.Value, }).ToList(); SortNodes(nodes); while (nodes.Count >= 2) { var nodeLeft = nodes[0]; var nodeRight = nodes[1]; nodes.RemoveAt(0); nodes.RemoveAt(0); var newNode = new HuffmanBinaryNode <T>() { LeftNode = nodeLeft, RightNode = nodeRight, Weight = nodeLeft.Weight + nodeRight.Weight }; nodes.Add(newNode); SortNodes(nodes); } return(new HuffmanTree <T>() { Root = nodes[0] }); }
void Step(HuffmanBinaryNode <T> currentNode, List <HuffmanPath.Path> currentPath) { if (currentNode.LeftNode == null) { Table.Add(currentNode.Value, currentPath); } else { var leftList = new List <HuffmanPath.Path>(currentPath); leftList.Add(HuffmanPath.Path.Left); Step(currentNode.LeftNode, leftList); var rightList = new List <HuffmanPath.Path>(currentPath); rightList.Add(HuffmanPath.Path.Right); Step(currentNode.RightNode, rightList); } }