哈夫曼编码

步骤:
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");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值