33,027
社区成员




class HaffManTree
{
//2、求赫夫曼树的WPL算法
private int[] Weight ={ 5 ,29 ,7 ,8 ,14 ,23 ,3 ,11 };
private List<TreeNode> Forest;//所有的haffman树上的有值的节点
private List<TreeNode> FinishedBuildNodes; //所有已经建立好关系的节点
public void InitialAll()
{
this.Forest = new List<TreeNode>();
this.FinishedBuildNodes = new List<TreeNode>();
for(int i=0;i<this.Weight.Length;i++)
{
TreeNode node=new TreeNode();
node.Value=Weight[i];
this.Forest.Add(node);
}
}
public void BuildTree()
{
while (this.Forest.Count > 1)
{
BuildSmallestTwoNodes();
}
FinishedBuildNodes.Add(Forest[0]);
}
private void BuildSmallestTwoNodes()
{
for(int i=1;i<Forest.Count;i++)
{
if (Forest[0].Value>Forest[i].Value)
{
swap(0 ,i);
}
}
for (int i = 2 ; i < Forest.Count ; i++)
{
if (Forest[1].Value > Forest[i].Value)
{
swap(1 ,i);
}
}
TreeNode node = new TreeNode();
node.Value = Forest[0].Value + Forest[1].Value;
node.IsRelationNode = true;
//最小两个移除
node.LeftChild = Forest[0];
FinishedBuildNodes.Add(Forest[0]);
Forest.RemoveAt(0);
node.RightChild = Forest[0];
FinishedBuildNodes.Add(Forest[0]);
Forest.RemoveAt(0);
//加入新的node
Forest.Add(node);
}
private void swap(int p ,int i)
{
TreeNode node = Forest[p];
Forest[p] = Forest[i];
Forest[i] = node;
}
}
class TreeNode
{
public bool IsRelationNode=false;
public Int32 Value;
public TreeNode LeftChild;
public TreeNode RightChild;
}