算法是准确的,目前程序还有一点点小bug
public class HTNode
{
String name; // name of node
int weight; //weight
int parent; //parent node
int lchild; //leftchild node
int rchild; //rightchild node
String Hcode; //huffman code
}
/**
* this program is to show how HuffmanTree work.
* to create huffmantree,and to huffmancode.
* @author NEU 小宇
* @version1.0
*/
public class Huffman
{
public HTNode[] ht;
public static final int LEAF_NODE_NUM = 6;
public Huffman()
{
ht = new HTNode[2*LEAF_NODE_NUM - 1]; //to initialize an array of nodes
for(int i = 0; i < 2*LEAF_NODE_NUM - 1; i++)
ht[i] = new HTNode();
ht[0].weight = 5;
ht[1].weight = 8;
ht[2].weight = 15;
ht[3].weight = 30;
ht[4].weight = 17;
ht[5].weight = 27;
ht[0].name = "a";
ht[1].name = "b";
ht[2].name = "c";
ht[3].name = "d";
ht[4].name = "e";
ht[5].name = "f";
}
public void createHuffman()
{
int i, j, k, lnode, rnode;
int min1, min2;
for(i = 0; i < 2*LEAF_NODE_NUM - 1; i++)
ht[i].parent = ht[i].lchild = ht[i].rchild = -1;
for(i = LEAF_NODE_NUM; i < 2*LEAF_NODE_NUM - 1 ; i++)
{
min1 = min2 = 32767;
lnode = rnode = -1;
for(k = 0; k <= i - 1; k++){
if(ht[k].parent == -1)
{
if(ht[k].weight < min1)
{
min2 = min1;
rnode = lnode;
min1 = ht[k].weight;
lnode = k;
}
else if(ht[k].weight < min2)
{
min2 = ht[k].weight;
rnode = k;
}
}
}
System.out.println(lnode+ " " + rnode);
ht[lnode].parent = i;
ht[rnode].parent = i;
ht[i].weight = ht[lnode].weight + ht[rnode].weight;
ht[i].lchild = lnode;
ht[i].rchild = rnode;
}
}
void CreateHCode(HTNode[] ht)
{
for(int i = 0; i < LEAF_NODE_NUM; i++ )
{
int f = ht[i].parent;
int c = i;
while(f != -1)
{
if(ht[f].lchild == c)
ht[i].Hcode = "0" + ht[i].Hcode;
else
ht[i].Hcode = "1" + ht[i].Hcode;
c = f;
f = ht[f].parent;
}
}
}
}
import java.util.Scanner;
/**Input the sting,
* then you'll get the Huffman code
*
* @author NEU 小宇
* @version1.0
*/
public class GetHuffmanCode
{
public static void main(String[] args)
{
Huffman huffman = new Huffman();
huffman.createHuffman();
huffman.CreateHCode(huffman.ht);
for(int i = 0; i < 6; i++)
System.out.print(huffman.ht[i].Hcode + " ");
Input(huffman);
}
public static void Input(Huffman hf)
{
System.out.println("Input string(5 letters of a,b,c,d,e,f):");
Scanner scanner = new Scanner(System.in);
String inputStr = scanner.next();
String subStr;
for(int i = 0; i < 5; i++)
{
subStr = inputStr.substring(i, i + 1);
if(subStr.equals("a"))
System.out.print(hf.ht[0].Hcode);
else if(subStr.equals("b"))
System.out.print(hf.ht[1].Hcode);
else if(subStr.equals("c"))
System.out.print(hf.ht[2].Hcode);
else if(subStr.equals("d"))
System.out.print(hf.ht[3].Hcode);
else if(subStr.equals("e"))
System.out.print(hf.ht[4].Hcode);
else if(subStr.equals("f"))
System.out.print(hf.ht[5].Hcode);
}
}
}