步骤:
1.创建森林。
2.创建哈夫曼树。
3.哈夫曼编码
这里写代码片
public class Haffum(){
public static void main(String[]args){
Haffum hf = new Haffum();
hf.creatHuffmTree();
hf.huffCode(hf.list.get(0),"");
}
//权重数组
int[] arry = { 5, 6, 2, 9, 7 };
LinkedList<MyNode> list = new LinkedList<MyNode>();
public void creatFroest(){
for(int i=0;i<arry.length;i++){
MyNode mynode = new MyNode();
myNode.settWeight(arry[i]);
list.add(mynode);
}
}
//获取最小权重值的节点
public MyNode getMin(){
int min = 0;
MyNode weight = list.get(0).getWeight();
for(int i=0;i<list.size();i++){
MyNode temp = list.get(i);
if(weight.getWeight>temp.getWeight){
min = i;
weight = temp;
}
}
MyNode remove = list.remove(min);
return remove;
}
//哈夫曼树
public void creatHuffmTree(){
creatForest();
while(list.size()!=1){
MyNode min1 = getMin();
MyNode min2 = getMin();
MyNode mynode = new MyNode();
mynode.setWeight(min1.getWeight+min2.getWeight);
mynode.setlChild(min1);
mynode.setrChild(min2);
}
pre(list.get(0));
}
//前序遍历
public void pre(MyNode root){
if(root==null)
return;
System.out.println(root.getWeight);
pre(root.getlChild());
pre(root.getrChild(););
}
//编码
public void huffCode(MyNode root,String code){
if(root==null)
return;
if(root.getlChild()==null & &root.getrChild()==null){
System.out.println(code);
return;
}
huffCode(root.getlChild(),code+"0");
huffCode(root.getrChild(),code+"1");
}
}