[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