packagecom.lin.HuffmanCode_0314;importjava.util.ArrayList;importjava.util.Collections;importjava.util.HashMap;importjava.util.List;importjava.util.Map;public classHuffmanCode {public static voidmain(String[] args) {
String content= "i like like like java do you like a java";byte[] contentBytes =content.getBytes();
System.out.println(contentBytes.length);//40
List nodes =getNodes(contentBytes);
System.out.println(nodes);//创建哈夫曼树
System.out.println("哈夫曼树");
Node createHuffmanTree=createHuffmanTree(nodes);
preOrder(createHuffmanTree);
}/***
* @Description:生成赫夫曼树对应的赫夫曼编码
* 思路:将赫夫曼编码存放在Map<
*@authorLinZM
* @date 2021-3-14 21:09:30
*@versionV1.8*/
//前序遍历
private static voidpreOrder(Node root){if(root != null) {
root.preOrder();
}else{
System.out.println("空树!");
}
}/***
* @Description:
*@authorLinZM
* @date 2021-3-14 20:45:23
*@versionV1.8
*@parambytes接收字节数组
*@param
*/
private static List getNodes(byte[] bytes){//1 创建一个ArrayList
ArrayList nodes= new ArrayList();//遍历bytes,统计每一个byte出现的次数->map[key, value]
Map counts = newHashMap();for(byteb: bytes) {
Integer count= counts.get(b); //
if(count == null) { //Map中还没有这个字符数据, 第一次
counts.put(b, 1);
}else{
counts.put(b, count+ 1);
}
}//把每个键值对转成一个Node对象, 并加入到nodes集合
for(Map.Entryentry: counts.entrySet()) {
nodes.add(newNode(entry.getKey(), entry.getValue()));
}returnnodes;
}//通过List创建赫夫曼树
private static Node createHuffmanTree(Listnodes) {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{
Byte data;//存放数据本身
int weight; //权值,字符出现的次数
Node left;
Node right;public Node(Byte data, intweight) {this.data =data;this.weight =weight;
}
@Overridepublic intcompareTo(Node o) {//TODO Auto-generated method stub
return this.weight -o.weight;
}
@OverridepublicString toString() {return "Node [data = " + data + " weight= " + weight + "]";
}//前序遍历
public voidpreOrder() {
System.out.println(this);if(this.left != null) {this.left.preOrder();
}if(this.right != null) {this.right.preOrder();
}
}
}