贪心算法应用-哈夫曼编码

学习哈夫曼编码,最大的收获是学习了贪心算法的实现套路:每次的选择都是局部最优解。但是贪心算法不能保证最后得到整体最优解。

 

public class HuffmanTree {

    public static   HuffmanNode createHuffmanTree(List> nodes) {
        //将散列的森林合并为树
        while(nodes.size() > 1){
            //按权重升序排列,前2个树的权重最小
            Collections.sort(nodes);
            HuffmanNode left = nodes.get(0);
            HuffmanNode right = nodes.get(1);
            HuffmanNode 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  void printHuffmanTree(HuffmanNode 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> 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 node = HuffmanTree.createHuffmanTree(huffmanTreeList);
        HuffmanTree.printHuffmanTree(node);
    }
}

 

public class HuffmanNode implements Comparable>{
    private T data;
    private int weight;
    private HuffmanNode left;
    private HuffmanNode 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 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 getLeft() {
        return left;
    }

    public void setLeft(HuffmanNode left) {
        this.left = left;
    }

    public HuffmanNode getRight() {
        return right;
    }

    public void setRight(HuffmanNode right) {
        this.right = right;
    }
}

 

你可能感兴趣的:(算法)