/// <summary> /// 创建哈夫曼树 /// </summary> public void Create() { while (tmpData.Count > 1) { //根据权重最小的两节点生成新节点 HuffmanTreeNode tmp = new HuffmanTreeNode(); tmp.Weight = tmpData[0].Weight + tmpData[1].Weight; tmp.LeftChild = tmpData[0].Index; tmp.RightChild = tmpData[1].Index; int newIndex = tmpData.Max(p => p.Index) + 1; tmp.Index = newIndex; //临时数组添加新生成的节点 tmpData.Add(tmp); //结果数据添加新生成的节点 data.Add(tmp); //临时数组移除已处理的节点 tmpData.RemoveAt(0); tmpData.RemoveAt(0); //重新排列临时数组 tmpData = tmpData.OrderBy(p => p.Weight).ToList(); } }
/// <summary> /// 构造函数 /// </summary> /// <param name="n"></param> public HuffmanTree(List <int> weights) { //根据权重节点设定数组大小 data = new List <HuffmanTreeNode>(2 * weights.Count - 1); tmpData = new List <HuffmanTreeNode>(2 * weights.Count - 1); //排列权重 weights = weights.OrderBy(p => p).ToList(); //按权重初始化哈夫曼数组 for (int i = 0; i < weights.Count; i++) { HuffmanTreeNode tmp = new HuffmanTreeNode(); tmp.Weight = weights[i]; tmp.Index = i; tmpData.Add(tmp); data.Add(tmp); } //设置叶子节点的数目 leafNum = weights.Count; }