学习哈夫曼编码,最大的收获是学习了贪心算法的实现套路:每次的选择都是局部最优解。但是贪心算法不能保证最后得到整体最优解。
public class HuffmanTree { public static <T> HuffmanNode<T> createHuffmanTree(List<HuffmanNode<T>> nodes) { //将散列的森林合并为树 while(nodes.size() > 1){ //按权重升序排列,前2个树的权重最小 Collections.sort(nodes); HuffmanNode<T> left = nodes.get(0); HuffmanNode<T> right = nodes.get(1); HuffmanNode<T> newNode = new HuffmanNode<>(null, left.getWeight() + right.getWeight()); newNode.setLeft(left); newNode.setRight(right); nodes.remove(left); nodes.remove(right); nodes.add(newNode); } return nodes.get(0); } public static <T> void printHuffmanTree(HuffmanNode<T> root) { if(root == null) return; System.out.println(root.toString()); if(root.getLeft() != null) printHuffmanTree(root.getLeft()); if(root.getRight() != null) printHuffmanTree(root.getRight()); } public static void main(String[] args) { List<HuffmanNode<String>> huffmanTreeList = new ArrayList<>(); huffmanTreeList.add(new HuffmanNode<>("d", 5)); huffmanTreeList.add(new HuffmanNode<>("c", 9)); huffmanTreeList.add(new HuffmanNode<>("g", 15)); huffmanTreeList.add(new HuffmanNode<>("a", 1)); huffmanTreeList.add(new HuffmanNode<>("q", 25)); HuffmanNode<String> node = HuffmanTree.createHuffmanTree(huffmanTreeList); HuffmanTree.printHuffmanTree(node); } }
public class HuffmanNode<T> implements Comparable<HuffmanNode<T>>{ private T data; private int weight; private HuffmanNode<T> left; private HuffmanNode<T> right; public HuffmanNode(T data, int weight){ this.data = data; this.weight = weight; } public String toString() { return "data:" + this.data +", weight:" + this.weight + "; "; } @Override public int compareTo(HuffmanNode<T> o) { //升序 if(this.weight < o.weight) return -1; else if(this.weight > o.weight) return 1; else return 0; } public T getData() { return data; } public void setData(T data) { this.data = data; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public HuffmanNode<T> getLeft() { return left; } public void setLeft(HuffmanNode<T> left) { this.left = left; } public HuffmanNode<T> getRight() { return right; } public void setRight(HuffmanNode<T> right) { this.right = right; } }