public HuffmanTree(params int[] weights) { if (weights.Length < 2) { throw new Exception("叶节点不能少于2个!"); } int n = weights.Length; Array.Sort(weights); //先生成叶子节点,并按weight从小到大排序 List <HuffNode> lstLeafs = new List <HuffNode>(n); for (int i = 0; i < n; i++) { var node = new HuffNode(); node.Weight = weights[i]; node.Index = i; lstLeafs.Add(node); } //创建临时节点容器 _tmp = new List <HuffNode>(2 * n - 1); //真正存放所有节点的容器 _nodes = new List <HuffNode>(_tmp.Capacity); _tmp.AddRange(lstLeafs); _nodes.AddRange(_tmp); }
/// <summary> /// 构造Huffman树 /// </summary> public void Create() { while (this._tmp.Count > 1) { var tmp = new HuffNode(this._tmp[0].Weight + this._tmp[1].Weight, _tmp[0].Index, _tmp[1].Index, this._tmp.Max(c => c.Index) + 1); this._tmp.Add(tmp); this._nodes.Add(tmp); //删除已经处理过的二个节点 this._tmp.RemoveAt(0); this._tmp.RemoveAt(0); //重新按权重值从小到大排序 this._tmp = this._tmp.OrderBy(c => c.Weight).ToList(); } }