package cn.mrlij.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HuffmanCode {
public static void main(String[] args) {
String str = "i like like like java do you like a java";
byte b[] = str.getBytes();
List<Node> nodes = getNodes(b);
System.out.println(nodes);
Node node = createHuffman(nodes);
node.preOrder();
}
//构建哈夫曼树
public static List<Node> getNodes(byte[] b){
List<Node> nodes = new ArrayList<>();
Map<Byte,Integer> map = new HashMap<>();
//遍历字节数组
for(byte bt : b) {
Integer count = map.get(bt);
if(count!=null) {
map.put(bt, count+1);
}else {
map.put(bt,1);
}
}
//依次创建树
for(Entry<Byte,Integer> entry : map.entrySet()) {
Node node = new Node(entry.getKey(),entry.getValue());
nodes.add(node);
}
return nodes;
}
public static Node createHuffman(List<Node> nodes) {
while(nodes.size()>1) {
//首先进行排序
Collections.sort(nodes);
//拿出集合中前两个最小的
Node left = nodes.get(0);
Node right = nodes.get(1);
//创建节点
Node parent = new Node(null,left.val+right.val);
parent.left = left;
parent.right = right;
//将两个节点从集合移除
nodes.remove(left);
nodes.remove(right);
//将父节点加入集合
nodes.add(parent);
}
return nodes.get(0);
}
public static void preOrder(Node root) {
if(root!=null) {
root.preOrder();
}else {
System.out.println("tree为空");
}
}
}
//创建Node,存放数据和权值
class Node implements Comparable<Node>{
Byte data;//具体的字符
int val;//表示字符出现的次数
Node left;//左节点
Node right;//右节点
@Override
public String toString() {
return "Node [data=" + data + ", val=" + val + "]";
}
public Node(Byte data, int val) {
this.data = data;
this.val = val;
}
//前序遍历
public void preOrder() {
System.out.println(this);
if(this.left!=null) {
this.left.preOrder();
}
if(this.right!=null) {
this.right.preOrder();
}
}
@Override
public int compareTo(Node o) {
return this.val-o.val;
}
}