一、赫夫曼树
基本介绍: 1、给定n个权值作为n个叶子结点,构造一棵二叉树,若该树的带权路径长度(wpl)达到最小,称这样的二叉树为最优二叉树,也称为赫夫曼树 2、赫夫曼树是带权路径长度最短的树,权值较大的结点离根较近
1、路径和路径长度:在一棵树中,从一个结点往下可以达到的孩子或孙子结点之间的通路,称为路径。通路中分支的数目称为路径长度。若规定根结点的层数为1,则从根结点到第L层结点的路径长度为L-1 2、结点的权和带权路径长度:若将树中结点赋给一个有着某种含义的数值,则这个数值称为该结点的权。结点的带权路径长度为:从根结点到该结点之间的路径长度与该结点的权的乘积 3、树的带权路径长度:树的带权路径长度规定为所有叶子结点的带权路径长度之和,记为WPL(weighted path length),权值越大的结点离根结点越近的二叉树才是最优二叉树 4、WPL最小的就是赫夫曼树
构成赫夫曼树的步骤: 1、从小到大进行排序,将每一个数据,每个数据都是一个结点,每个结点可以看成是一棵最简单的二叉树 2、取出根结点权值最小的两棵二叉树 3、组成一棵新的二叉树,该新的二叉树的根结点的权值是前面两棵二叉树根结点权值的和 4、再将这颗新的二叉树,以根结点的权值大小再次排序,不断重复1234步骤,直到数列中,所有的数据都被处理,就得到一棵赫夫曼树
package huffmantree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HuffmanTree {
public static void main(String[] args) {
int[] arr = {13, 7, 8, 3, 29, 6, 1};
Node root = createHuffmanTree(arr);
preOrder(root);
}
public static Node createHuffmanTree(int[] arr){
List<Node> nodes = new ArrayList<>();
for (int value : arr) {
nodes.add(new Node(value));
}
while (nodes.size() > 1){
Collections.sort(nodes);
Node leftNode = nodes.get(0);
Node rightNode = nodes.get(1);
Node parent = new Node(leftNode.value + rightNode.value);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
public static void preOrder(Node root){
if (root != null) {
root.preOrder();
} else {
System.out.println("空树,无法遍历");
}
}
}
class Node implements Comparable<Node>{
int value;
Node left;
Node right;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return "Node{" +
"value=" + value +
'}';
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
public void preOrder(){
System.out.println(this);
if (this.left != null){
this.left.preOrder();
}
if (this.right != null){
this.right.preOrder();
}
}
}
二、赫夫曼编码
赫夫曼编码也叫哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式,属于一种程序算法,赫夫曼编码广泛地用于数据文件压缩,其压缩率通常在20%-90%之间。
注意: 赫夫曼树根据排序方法不同,也可能不太一样,这样对应的赫夫曼编码也不完全一样,但是wpl是一样的,都是最小的,最后生成的赫夫曼编码的长度是一样的
2.1 数据压缩-创建赫夫曼树
功能:根据赫夫曼编码压缩数据的原理,需要创建"i like like like java do you like a java"对应的赫夫曼树 思路: 1、Node{data (存放数据), weight(权值), left和right} 2、得到"i like like like java do you like a java"对应的byte[]数组 3、编写一个方法,将准备构建赫夫曼树的Node结点放到List中,形式如{Node[data=7,weight=5],Node[data=32,weight=9]…} 4、通过List创建对应的赫夫曼树
private static Node createHuffmanTree(List<Node> nodes){
while (nodes.size() > 1){
Collections.sort(nodes);
Node leftNode = nodes.get(0);
Node rightNode = nodes.get(1);
Node parent = new Node(null, leftNode.weight + rightNode.weight);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
2.2 生成赫夫曼编码和赫夫曼编码后的数据
static Map<Byte, String> huffmanCodes = new HashMap<>();
static StringBuilder stringBuilder = new StringBuilder();
private static Map<Byte, String> getCodes(Node root){
if (root == null){
return null;
}
getCodes(root.left,"0",stringBuilder);
getCodes(root.right,"1",stringBuilder);
return huffmanCodes;
}
private static void getCodes(Node node, String code, StringBuilder stringBuilder){
StringBuilder stringBuilder1 = new StringBuilder(stringBuilder);
stringBuilder1.append(code);
if (node != null){
if (node.data == null){
getCodes(node.left, "0", stringBuilder1);
getCodes(node.right, "1", stringBuilder1);
}else {
huffmanCodes.put(node.data, stringBuilder1.toString());
}
}
}
2.3 数据解压-使用赫夫曼编码解码
private static String byteToBitString(boolean flag, byte b){
int temp = b;
if (flag){
temp |= 256;
}
String str = Integer.toBinaryString(temp);
if (flag){
return str.substring(str.length() - 8);
}else {
return str;
}
}
private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes){
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < huffmanBytes.length; i++){
byte b = huffmanBytes[i];
boolean flag = (i == huffmanBytes.length - 1);
stringBuilder.append(byteToBitString(!flag, b));
}
Map<String, Byte> map = new HashMap<>();
for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()){
map.put(entry.getValue(), entry.getKey());
}
List<Byte> list = new ArrayList<>();
for (int i = 0; i < stringBuilder.length();){
int count = 1;
boolean flag = true;
Byte b = null;
while (flag){
String key = stringBuilder.substring(i, i + count);
b = map.get(key);
if (b == null){
count++;
}else {
flag = false;
}
}
list.add(b);
i += count;
}
byte b[] = new byte[list.size()];
for (int i = 0; i < b.length; i++){
b[i] = list.get(i);
}
return b;
}
2.4 文件压缩
public static void zipFile(String srcFile, String dstFile){
OutputStream os = null;
ObjectOutputStream oos = null;
FileInputStream is = null;
try {
is = new FileInputStream(srcFile);
byte[] b = new byte[is.available()];
is.read(b);
byte[] huffmanBytes = huffmanZip(b);
os = new FileOutputStream(dstFile);
oos = new ObjectOutputStream(os);
oos.writeObject(huffmanBytes);
oos.writeObject(huffmanCodes);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
is.close();
oos.close();
os.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
2.5 文件解压(文件恢复)
public static void unzipFile(String zipFile, String dstFile){
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
try {
is = new FileInputStream(zipFile);
ois = new ObjectInputStream(is);
byte[] huffmanBytes = (byte[])ois.readObject();
Map<Byte, String> huffmanCodes = (Map<Byte, String>)ois.readObject();
byte[] bytes = decode(huffmanCodes, huffmanBytes);
os = new FileOutputStream(dstFile);
os.write(bytes);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
os.close();
ois.close();
is.close();
}catch (Exception e2){
System.out.println(e2.getMessage());
}
}
}
赫夫曼编码压缩文件注意事项 1、如果文件本身就是经过压缩处理的,那么使用赫夫曼编码再压缩效率不会有明显变化,比如视频、ppt等文件 2、赫夫曼编码是按字节来处理的,因此可以处理所有的文件(二进制文件、文本文件) 3、如果一个文件中的内容,重复的数据不多,压缩效果也不会很明显
2.6 代码汇总
package huffmancode;
import java.io.*;
import java.util.*;
public class HuffmanCode {
public static void main(String[] args) {
String zipFile = "E:\\1.zip";
String dstFile = "E:\\1234.tif";
unzipFile(zipFile,dstFile);
System.out.println("解压文件ok");
}
public static void unzipFile(String zipFile, String dstFile){
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
try {
is = new FileInputStream(zipFile);
ois = new ObjectInputStream(is);
byte[] huffmanBytes = (byte[])ois.readObject();
Map<Byte, String> huffmanCodes = (Map<Byte, String>)ois.readObject();
byte[] bytes = decode(huffmanCodes, huffmanBytes);
os = new FileOutputStream(dstFile);
os.write(bytes);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
os.close();
ois.close();
is.close();
}catch (Exception e2){
System.out.println(e2.getMessage());
}
}
}
public static void zipFile(String srcFile, String dstFile){
OutputStream os = null;
ObjectOutputStream oos = null;
FileInputStream is = null;
try {
is = new FileInputStream(srcFile);
byte[] b = new byte[is.available()];
is.read(b);
byte[] huffmanBytes = huffmanZip(b);
os = new FileOutputStream(dstFile);
oos = new ObjectOutputStream(os);
oos.writeObject(huffmanBytes);
oos.writeObject(huffmanCodes);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
is.close();
oos.close();
os.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes){
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < huffmanBytes.length; i++){
byte b = huffmanBytes[i];
boolean flag = (i == huffmanBytes.length - 1);
stringBuilder.append(byteToBitString(!flag, b));
}
Map<String, Byte> map = new HashMap<>();
for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()){
map.put(entry.getValue(), entry.getKey());
}
List<Byte> list = new ArrayList<>();
for (int i = 0; i < stringBuilder.length();){
int count = 1;
boolean flag = true;
Byte b = null;
while (flag){
String key = stringBuilder.substring(i, i + count);
b = map.get(key);
if (b == null){
count++;
}else {
flag = false;
}
}
list.add(b);
i += count;
}
byte b[] = new byte[list.size()];
for (int i = 0; i < b.length; i++){
b[i] = list.get(i);
}
return b;
}
private static String byteToBitString(boolean flag, byte b){
int temp = b;
if (flag){
temp |= 256;
}
String str = Integer.toBinaryString(temp);
if (flag){
return str.substring(str.length() - 8);
}else {
return str;
}
}
private static byte[] huffmanZip(byte[] bytes){
List<Node> nodes = getNodes(bytes);
Node huffmanTreeRoot = createHuffmanTree(nodes);
Map<Byte, String> huffmanCodes = getCodes(huffmanTreeRoot);
byte[] huffmanCodeBytes = zip(bytes, huffmanCodes);
return huffmanCodeBytes;
}
private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes){
StringBuilder stringBuilder = new StringBuilder();
for(byte b : bytes){
stringBuilder.append(huffmanCodes.get(b));
}
int len;
if (stringBuilder.length() % 8 == 0){
len = stringBuilder.length() / 8;
}else {
len = stringBuilder.length() / 8 + 1;
}
byte[] huffmanCodeBytes = new byte[len];
int index = 0;
for (int i = 0; i < stringBuilder.length(); i += 8){
String strByte;
if (i + 8 > stringBuilder.length()){
strByte = stringBuilder.substring(i);
}else {
strByte = stringBuilder.substring(i, i + 8);
}
huffmanCodeBytes[index] = (byte) Integer.parseInt(strByte, 2);
index++;
}
return huffmanCodeBytes;
}
static Map<Byte, String> huffmanCodes = new HashMap<>();
static StringBuilder stringBuilder = new StringBuilder();
private static Map<Byte, String> getCodes(Node root){
if (root == null){
return null;
}
getCodes(root.left,"0",stringBuilder);
getCodes(root.right,"1",stringBuilder);
return huffmanCodes;
}
private static void getCodes(Node node, String code, StringBuilder stringBuilder){
StringBuilder stringBuilder1 = new StringBuilder(stringBuilder);
stringBuilder1.append(code);
if (node != null){
if (node.data == null){
getCodes(node.left, "0", stringBuilder1);
getCodes(node.right, "1", stringBuilder1);
}else {
huffmanCodes.put(node.data, stringBuilder1.toString());
}
}
}
private static void preOrder(Node root){
if (root != null){
root.preOrder();
}else {
System.out.println("赫夫曼树为空");
}
}
private static List<Node> getNodes(byte[] bytes){
ArrayList<Node> nodes = new ArrayList<>();
Map<Byte, Integer> counts = new HashMap<>();
for(byte b : bytes){
Integer count = counts.get(b);
if (count == null){
counts.put(b, 1);
}else {
counts.put(b, count + 1);
}
}
for (Map.Entry<Byte, Integer> entry : counts.entrySet()){
nodes.add(new Node(entry.getKey(), entry.getValue()));
}
return nodes;
}
private static Node createHuffmanTree(List<Node> nodes){
while (nodes.size() > 1){
Collections.sort(nodes);
Node leftNode = nodes.get(0);
Node rightNode = nodes.get(1);
Node parent = new Node(null, leftNode.weight + rightNode.weight);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
}
class Node implements Comparable<Node>{
Byte data;
int weight;
Node left;
Node right;
public Node(Byte data, int weight) {
this.data = data;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return this.weight - o.weight;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", weight=" + weight +
'}';
}
public void preOrder(){
System.out.println(this);
if (this.left != null){
this.left.preOrder();
}
if (this.right != null){
this.right.preOrder();
}
}
}
|