Huffman编码小例子
Huffman编码小例子
package week10_01;
import java.util.HashMap;
import java.util.PriorityQueue;
/**
* 哈弗曼编码
* @author Guozhu Zhu
* @date 2019/5/6
* @version 1.0
*
*/
public class Huffman04 {
private class Node implements Comparable<Node> {
char ch; //字符
int freq; //权值
boolean isLeaf; //是否叶子
Node left; //左孩子
Node right; //右孩子
public Node(char ch, int freq) {
this.ch = ch;
this.freq = freq;
this.isLeaf = true;
}
public Node(Node left, Node right, int freq) {
this.left = left;
this.right = right;
this.freq = freq;
this.isLeaf = false;
}
@Override
public int compareTo(Node o) {
// TODO Auto-generated method stub
return this.freq - o.freq;
}
}
public HashMap<Character, String> encode(HashMap<Character, Integer> frequencyOfChar) {
PriorityQueue<Node> priorityQueue = new PriorityQueue<Node>();
for (Character ch : frequencyOfChar.keySet()) {
priorityQueue.offer(new Node(ch, frequencyOfChar.get(ch)));
}
while (priorityQueue.size() != 1) {
Node node1 = priorityQueue.poll();
Node node2 = priorityQueue.poll();
priorityQueue.offer(new Node(node1, node2, node1.freq+node2.freq));
}
return encode(priorityQueue.poll());
}
public HashMap<Character, String> encode(Node root) {
HashMap<Character, String> encodingOfChar = new HashMap<Character, String>();
encode(root, "", encodingOfChar);
return encodingOfChar;
}
public void encode(Node root, String encoding, HashMap<Character, String> encodingOfChar) {
if (root.isLeaf) {
encodingOfChar.put(root.ch, encoding);
return;
}
encode(root.left, encoding + "0", encodingOfChar);
encode(root.right, encoding + "1", encodingOfChar);
}
/* ========== Test ========== */
public static void main(String[] args) {
Huffman04 huffman = new Huffman04();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('a', 10);
map.put('b', 20);
map.put('c', 40);
map.put('d', 80);
HashMap<Character, String> res = huffman.encode(map);
System.out.println(res);
}
}