算法java实现--贪心算法--哈弗曼编码

哈弗曼编码的java实现(贪心算法)

具体问题描述以及C/C++实现参见网址

http://blog.csdn.net/liufeng_king/article/details/8720896

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
 * 哈弗曼树(贪心算法)
 * @author Lican
 *
 */
public  class Huffman implements Comparable {
	Bintree tree;
	float weight;
	String coding;
	public Huffman(Bintree tree,float weight){
		this.tree=tree;
		this.weight=weight;
	}
	@Override
	public int compareTo(Object x) {
		float w=((Huffman)x).weight;
		if(this.weight<w) return -1;
		if(this.weight==w) return 0;
		return 1;
		
	}
	/**
	 * 二叉树类
	 * @author Lican
	 *
	 */
	public static class Bintree{
		public Bintree Left;
		public Bintree Right;
		public String data;
		public String coding;
		public Bintree(Bintree l,Bintree r,String data){
			this.Left=l;
			this.Right=r;
			this.data=data;
		}
		public String getCoding() {
			return coding;
		}
		public void setCoding(String coding) {
			this.coding = coding;
		}
		
	}
	/**
	 * 创建Huffman树
	 * @param h
	 * @return
	 */
	public static Huffman createHuffmanTree(List<Huffman> h){		
		while(h.size()>1){
			Collections.sort(h);
			Huffman h1=h.get(0);
			Huffman h2=h.get(1);
			float w=h1.weight+h2.weight;
			Bintree b1=h1.tree;
			Bintree b2=h2.tree;
			Bintree b=new Bintree(b1,b2,"");
			Huffman node=new Huffman(b,w);
			h.remove(0);
			h.remove(0);
			h.add(node);
		}
		return h.get(0);
	}
	/**
	 * 根据树来编码,左子树分配0,右子树分配1
	 * @param node
	 * @param str
	 */
	public static void process(Bintree node,String str){  
        //叶子结点  
        if(node.Left==null){  
            node.setCoding(str); 
            System.out.println(node.data+": "+node.coding);
            return;  
        }  
        //对左子树分配代码"0"  
        process(node.Left,str+"0");  
        //对右子树分配代码"1"  
        process(node.Right,str+"1");  
    } 
	public static void main(String[] args) {
		List<Huffman> h=new ArrayList<Huffman>();
		Bintree b1=new Bintree(null,null,"A");
		Huffman h1=new Huffman(b1,40);
		h.add(h1);
		Bintree b2=new Bintree(null,null,"B");
		Huffman h2=new Huffman(b2,8);
		h.add(h2);
		Bintree b3=new Bintree(null,null,"C");
		Huffman h3=new Huffman(b3,10);
		h.add(h3);
		Bintree b4=new Bintree(null,null,"D");
		Huffman h4=new Huffman(b4,30);
		h.add(h4);
		Bintree b5=new Bintree(null,null,"E");
		Huffman h5=new Huffman(b5,10);
		h.add(h5);
		Bintree b6=new Bintree(null,null,"F");
		Huffman h6=new Huffman(b6,2);
		h.add(h6);
		Huffman root=createHuffmanTree(h);
		process(root.tree,"");
	}
}
/**
A: 0
D: 10
F: 1100
B: 1101
C: 1110
E: 1111
*/

    原文作者:贪心算法
    原文地址: https://blog.csdn.net/lican19911221/article/details/25539695
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞