霍夫曼编码的具体步骤如下
1)将信源符号的概率按减小的顺序排队。
2)把两个最小的概率相加,并继续这一步骤,始终将较高的概率分支放在右边,直到最后变成概率1。
3)画出由概率1处到每个信源符号的路径,顺序记下沿路径的0和1,所得就是该符号的霍夫曼码字。
4)将每对组合的左边一个指定为0,右边一个指定为1(或相反)
- 思路:一个节点类包括权重,父亲左儿子,右儿子节点,flag 的false表示已经使用过了,下次找两个最小的不会再找这个false掉的了,parentPath表示儿子到父亲的路径上的数字,左边为0,右边为1(我这个里面设置了左边儿子比右边儿子小),存储哈夫曼节点;然后一个list存储刚输入的码的权重生成的节点,每次查找flag为true的两个最小的权重的节点,生成父节点,设置相关节点的属性值;最后输出编码,不用遍历树,直接找到要编码的码,然后一路向上查找parentPath的值就是编码的倒序,故采用栈来保存,最后输出编码就是正确的编码格式。
- 话不多说,上代码:
package com.leibobo;
/**
* Created by bobolei 18/4/13
*哈夫曼节点定义
*/
public class NodeHuffman {
private int weight;
private boolean flag;
private int parentPath;
public int getParentPath() {
return parentPath;
}
public void setParentPath(int parentPath) {
this.parentPath = parentPath;
}
private NodeHuffman parent,lChild,rChild;
public NodeHuffman(){
}
public NodeHuffman(int weight){
this.weight = weight;
flag = true;
parent = lChild = rChild = null;
}
public int getWeight() {
return weight;
}
public