import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HafuManCode {
public static void main(String[] args) {
String content = "i like like like java do you like java";
byte[] contentBytes = content.getBytes();
System.out.println(contentBytes.length);//38
ArrayList<Node> nodes = creatList(contentBytes);
System.out.println(nodes);
System.out.println("------------");
Node node = creatTree(nodes);
node.preList(node);
}
//
public static ArrayList<Node> creatList(byte[] arr){
ArrayList<Node> nodes = new ArrayList<>();
//统计各个字符出现次数
HashMap<Byte, Integer> hashMap = new HashMap<>();
for (byte b : arr) {
Integer i = hashMap.get(b);
if (i == null){
hashMap.put(b,1);
}else {
hashMap.put(b,i+1);
}
}
//将每一个键值对转换成node对象放入集合
for (Map.Entry<Byte, Integer> entry : hashMap.entrySet()) {
nodes.add(new Node(entry.getKey(),entry.getValue()));
}
return nodes;
}
//构建哈夫曼数
public static Node creatTree(ArrayList<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.getWeight() + rightnode.getWeight());
//将左右子树挂在父节点上
parent.setLeft(leftnode);
parent.setRight(rightnode);
//将父节点添加进集合
nodes.add(parent);
//删除原来的数
nodes.remove(leftnode);
nodes.remove(rightnode);
}
return nodes.get(0);
}
}
//创建节点
class Node implements Comparable<Node> {
private Byte data;
private int weight;
private Node left;
private Node right;
//前序遍历
public void preList(Node root){
System.out.println(root);
//遍历左节点
if (root.left != null){
preList(root.left);
}
//遍历右节点
if (root.right != null){
preList(root.right);
}
}
public Node() {
}
public Node(Byte data, int weight) {
this.data = data;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return this.weight - o.weight;
}
/**
* 获取
* @return data
*/
public byte getData() {
return data;
}
/**
* 设置
* @param data
*/
public void setData(Byte data) {
this.data = data;
}
/**
* 获取
* @return weight
*/
public int getWeight() {
return weight;
}
/**
* 设置
* @param weight
*/
public void setWeight(int weight) {
this.weight = weight;
}
/**
* 获取
* @return left
*/
public Node getLeft() {
return left;
}
/**
* 设置
* @param left
*/
public void setLeft(Node left) {
this.left = left;
}
/**
* 获取
* @return right
*/
public Node getRight() {
return right;
}
/**
* 设置
* @param right
*/
public void setRight(Node right) {
this.right = right;
}
public String toString() {
return "Node{data = " + data + ", weight = " + weight + "}";
}
}
Java数据结构----哈夫曼编码
最新推荐文章于 2024-08-16 22:20:39 发布