zoukankan      html  css  js  c++  java
  • 使用优先队列实现Huffman树

     1 package com.mmall.common.Test;
     2 
     3 import java.util.Comparator;
     4 import java.util.PriorityQueue;
     5 import java.util.Queue;
     6 
     7 /**
     8  * Created by Workstation on 2017/8/9.
     9  */
    10 public class HuffmanCode {
    11 
    12    private class HuffNode implements Comparable<HuffNode>
    13     {
    14         HuffNode Left;
    15         HuffNode Right;
    16         int val;
    17 
    18         public HuffNode (HuffNode left, HuffNode right, int val) {
    19             Left = left;
    20             Right = right;
    21             this.val = val;
    22         }
    23 
    24         @Override
    25         public int compareTo (HuffNode o) {
    26             return this.val-o.val;
    27         }
    28     }
    29 
    30 
    31 
    32 
    33     public void CreateHuffmanTree(int [] weight)
    34     {
    35         //创建一个优先的队列;其中的值按照最小堆方式创建
    36         PriorityQueue<HuffNode> priorityQueue=new PriorityQueue<HuffNode> ();
    37 
    38 
    39         for(int i=0;i<weight.length;i++)
    40         {
    41             HuffNode node=new HuffNode (null,null,weight[i]);
    42             priorityQueue.add(node);
    43         }
    44 
    45         HuffNode node1=null;// 最小权值点
    46         HuffNode node2=null;// 次最小权值点
    47         HuffNode node3=null;//合并的值
    48 
    49         for(int j=0;j<weight.length-1;j++)
    50         {
    51             node1=priorityQueue.poll ();
    52             node2=priorityQueue.poll ();
    53             node3=new HuffNode (node1,node2,node1.val+node2.val);
    54             priorityQueue.offer(node3);
    55         }
    56 
    57         System.out.println(priorityQueue.peek ().val);
    58     }
    59 }
  • 相关阅读:
    beeline链接hive报错
    Java并发之FairSync和NonfairSync
    如何在 Linux 中将文件编码转换为 UTF-8
    Spring Boot运行原理
    jvm垃圾回收
    jvm调试工具
    Nginx相关
    docker 配置jar ,运行
    centos7的一些安装问题
    Docker
  • 原文地址:https://www.cnblogs.com/woainifanfan/p/7411549.html
Copyright © 2011-2022 走看看