哈夫曼树、编码介绍
哈夫曼树
给定N个权值作为N个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。哈夫曼树是带权路径长度最短的树,权值较大的结点离根较近。
哈夫曼编码
哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式,哈夫曼编码是可变字长编码(VLC)的一种。 Huffman于1952年提出一种编码方法,该方法完全依据字符出现概率来构造异字头的平均长度最短的码字,有时称之为最佳编码,一般就叫做Huffman编码(有时也称为霍夫曼编码)。
代码(含注释)
package 树;
import lombok.Data;
import sun.misc.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
// 编码,解码测试
class TestCode {
public static void main(String[] args) {
// String str = "abcde";
// String str = "ab";
String str = "Huffman code test";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
HuffmanCode huffmanCode = new HuffmanCode(bytes);
System.out.println("- - - - - - - - - - - ");
System.out.println("编码映射:");
for (Map.Entry<Byte, String> entry : huffmanCode.getCodeMap().entrySet()) {
System.out.println((char) entry.getKey().byteValue() + "->" + entry.getValue());
}
System.out.println("- - - - - - - - - - - ");
byte[] zipBytes = HuffmanCode.coding(huffmanCode.getCodeMap(), bytes);
byte[] decodingBytes = HuffmanCode.decoding(huffmanCode.getCodeMap(), zipBytes);
System.out.println("压缩后 = " + Arrays.toString(zipBytes));
System.out.println("解压后 = " + Arrays.toString(decodingBytes));
System.out.println("原字符串: " + str);
System.out.println("还原结果: " + new String(decodingBytes));
}
}
// 文件压缩,解压测试
class TestZip {
public static void main(String[] args) {
String orgPath, destPath;
Scanner scan = new Scanner(System.in);
System.out.println("待压缩文件路径:");
orgPath = scan.next();
//压缩
int endIndexOfPoint = orgPath.lastIndexOf('.');
destPath = orgPath.substring(0, endIndexOfPoint) + ".zip";
HuffmanCode.zip(orgPath, destPath);
System.out.println("已将 " + orgPath + " 压缩到:" + destPath);
//解压
orgPath = orgPath.substring(0, endIndexOfPoint) + "(1)" + orgPath.substring(endIndexOfPoint);
HuffmanCode.unZip(destPath, orgPath);
System.out.println("已将 " + destPath + " 解压到:" + orgPath);
scan.close();
}
}
/**
* Desc: 哈夫曼树
* 当用 n 个结点(都做叶子结点且都有各自的权值)试图构建一棵树时,
* 如果构建的这棵树的带权路径长度最小,称这棵树为“最优二叉树”,
* 有时也叫“赫夫曼树”或者“哈夫曼树”。
*
* @author pikachu
* @date: 2022/8/15 14:44
*/
@Data
public class HuffmanCode {