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 }
时间: 2024-10-05 16:49:25