C # example code

Source: Internet
Author: User

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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.