1、哈夫曼树
哈夫曼编码使用哈夫曼树的数据结构,哈夫曼树图解如下,即构造一个带权路径最小的数;
2、哈夫曼编码
使用哈夫曼树生成哈夫曼编码,已实现减少传输中数据的冗余;截取网络课程中的几张图来说明;
3、代码实现
package tree.huffmanTree.huffmanCode;
public class HuffmenNode implements Comparable<HuffmenNode> {
//存储的字符(用Byte不用byte的原因是,对于新创建的节点是没有字符的,即data可能为null)
Byte data;
//权重(记录出现的次数)
int weight;
HuffmenNode leftNode;
HuffmenNode rightNode;
public HuffmenNode(Byte data, int weight) {
this.data = data;
this.weight = weight;
}
@Override
public String toString() {
return "HuffmenNode{" +
"data=" + data +
", weight=" + weight +
'}';
}
@Override
public int compareTo(HuffmenNode o) {
return o.weight - this.weight;
}
}
package tree.huffmanTree.huffmanCode;
import java.io.*;
import java.util.*;
public class HuffmenCodeTest {
public static void main(String[] args) {
String msg = "can you can a can as a can canner can a can.";
byte[] bytes = msg.getBytes();
System.out.println(Arrays.toString(bytes));
System.out.println("压缩前的数据长度:" + bytes.length);
//使用赫夫曼编码压缩
byte[] tar = huffmenZip(bytes);
System.out.println("压缩后的数据长度:" + tar.length);
//使用赫夫曼编码表解压
byte[] sourceByte = decodeByHuffmen(tar, mapCode);
System.out.println(new String(sourceByte));
String src = "D:\\javaproject\\DataStructure\\src\\tree\