C#求解哈夫曼樹,執行個體代碼

來源:互聯網
上載者:User

複製代碼 代碼如下: 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;

//擷取數組中最小的2個值
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;
}
}

//樹的結點(樹是用數組儲存的)

public class Node
{
public int Weight { get; set; }//權值
public int LChild { get; set; }//左孩子在數組中的位置
public int RChild { get; set; }//右孩子在數組中的位置
public int Parent { get; set; }//父節點在數組中的位置
public Node()
{
Weight = 0;
LChild = -1;
RChild = -1;
Parent = -1;//-1表示沒有
}
public Node(int weight,int lChild,int rChild,int parent )
{
this.Weight = weight;
this.LChild = lChild;
this.RChild = rChild;
this.Parent = parent;
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.