(Ha) Heman tree (Java version)

Source: Internet
Author: User

[Java]
Package D0727;
 
Public class HuffmanTree {
Class HuffmanNode {
Int w; // weight
Int lChild, rChild, parent; // left and right children and parent nodes
 
Public HuffmanNode (int w ){
This. w = w;
LChild = rChild = parent =-1;
}
}
 
Int n;
HuffmanNode [] huffman;
 
// Find two minimum values from huffman and save the small values to m1 and m2.
Int m1, m2;
Public void selectMin (){
// Find the smallest
Int minw = Integer. MAX_VALUE;
For (int I = 0; I <n; I ++ ){
If (huffman [I]. w <minw & huffman [I]. parent =-1 ){
Minw = huffman [I]. w;
M1 = I;
}
}
// Small search times
Minw = Integer. MAX_VALUE;
For (int I = 0; I <n; I ++ ){
If (huffman [I]. w <minw & huffman [I]. parent =-1 & I! = M1 ){
Minw = huffman [I]. w;
M2 = I;
}
}
}

// Create a Heman tree
Public void buildHuffmanTree (int [] w ){
N = w. length;
Huffman = new HuffmanNode [2 * n-1];

For (int I = 0; I <n; I ++)
Huffman [I] = new HuffmanNode (w [I]);
For (int I = n; I <2 * n-1; I ++)
Huffman [I] = new HuffmanNode (-1 );

While (n // Select two nodes with the smallest weight from huffman to build a new node
SelectMin ();
// Create a new node
Huffman [n]. w = huffman [m1]. w + huffman [m2]. w;
Huffman [n]. lChild = m1;
Huffman [n]. rChild = m2;
// Modify the parent node pointer of m1 and m2
Huffman [m1]. parent = n;
Huffman [m2]. parent = n ++;

}
 
}
// Calculate the length of the weighted path
Public int WPL (int [] w ){
Int sum = 0;
For (int I = 0; I <w. length; I ++ ){
Int p = huffman [I]. parent;
Int ans = 0;
While (p! =-1 ){
Ans ++;
P = huffman [p]. parent;
}
Sum + = ans * w [I];
}
Return sum;
}
// Test
Public void test (){
Int [] w = {7, 5, 2, 4 };
BuildHuffmanTree (w );
Int r = WPL (w );
System. out. println (r );
}
 
Public static void main (String [] args ){
New HuffmanTree (). test ();
}
 
}
Author: lhfight

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.