Copy codeThe Code is as follows: class HuffmanTree
{
Private Node [] data;
Public int LeafNum {get; set ;}
Public Node this [int index]
{
Get {return data [index];}
Set {data [index] = value ;}
}
Public HuffmanTree (int n)
{
Data = new Node [2 * n-1];
For (int I = 0; I <2 * n-1; I ++)
{
Data [I] = new Node ();
}
LeafNum = n;
}
Public void Create (List <int> list)
{
Int min1;
Int min2;
Int tmp1, tmp2;
For (int I = 0; I <list. Count; I ++)
{
Data [I]. Weight = list [I];
}
For (int I = 0; I <LeafNum-1; I ++)
{
Min1 = min2 = int. MaxValue;
Tmp1 = tmp2 = 0;
// Obtain the minimum two values in the array
For (int j = 0; j <LeafNum + I; j ++)
{
If (data [j]. Weight <min1 & data [j]. Parent =-1)
{
Min2 = min1;
Tmp2 = tmp1;
Min1 = data [j]. Weight;
Tmp1 = j;
}
Else if (data [j]. Weight <min2 & data [j]. Parent =-1)
{
Min2 = data [j]. Weight;
Tmp2 = j;
}
}
Data [tmp1]. Parent = this. LeafNum + I;
Data [tmp2]. Parent = this. LeafNum + I;
Data [this. LeafNum + I]. Weight = data [tmp1]. Weight + data [tmp2]. Weight;
Data [this. LeafNum + I]. LChild = tmp1;
Data [this. LeafNum + I]. RChild = tmp2;
}
}
// Tree node (the tree is saved using arrays)
Public class Node
{
Public int Weight {get; set;} // Weight
Public int LChild {get; set;} // left child's position in the array
Public int RChild {get; set;} // The Position of the right child in the array
Public int Parent {get; set;} // position of the Parent node in the array
Public Node ()
{
Weight = 0;
LChild =-1;
RChild =-1;
Parent =-1; //-1 indicates no
}
Public Node (int weight, int lChild, int rChild, int parent)
{
This. Weight = weight;
This. LChild = lChild;
This. RChild = rChild;
This. Parent = parent;
}
}