java哈夫曼树实现
关于比较器的使用
返回-1 升序排列
返回1 降序排列注意:如果double值太小转int变0,则按原顺序排列,如有需要可加一个正负判断,再进行转换.
PriorityQueue
优先队列,接收容量和排列方式值如PriorityQueue(100,-1)
第二个参数可由函数式接口替代.
创建哈夫曼树,得到哈夫曼编码,编码得到节点值和权值
import java.util.Comparator;
import java.util.PriorityQueue;
public class Huffman {
final int MaxN=100;
int[] w;
String str;
static int wn;
static HTNode[] ht;
static String[] hcd;
public Huffman()
{
ht=new HTNode[MaxN];
hcd=new String[MaxN];
w=new int[MaxN];
}
public void init(int wn,int[] w,String str)
{
this.wn=wn;
for(int index=0;index<wn;index++)
{
this.w[index]=w[index];
}
this.str=str;
}
public void createHT()
{
Comparator<HTNode> priComparator=new Comparator<HTNode>() {
@Override
public int compare(HTNode o1, HTNode o2) {
// TODO Auto-generated method stub
return (int) (o1.getweight()-o2.getweight());
}
};
PriorityQueue<HTNode> que=new PriorityQueue<>(100,priComparator);
for(int index=0;index<wn;index++)
{
ht[index]=new HTNode();
ht[index].parent=null;
ht[index].data=str.charAt(index);
ht[index].weight=w[index];
que.offer(ht[index]);
}
//create new node
for(int index=wn;index<(2*wn-1);index++)
{
HTNode p1=que.poll();
System.out.println("p1:"+p1.weight);
HTNode p2=que.poll();
System.out.println("p2:"+p2.weight);
ht[index]=new HTNode();
p1.parent=ht[index];
p2.parent=ht[index];
ht[index].weight=p1.weight+p2.weight;
ht[index].lchild=p1;
p1.flag=true;
ht[index].rchild=p2;
p2.flag=false;
que.offer(ht[index]);//into the queue
}
}
public static HTNode transfromtoCode()
{
HTNode p = null;
for(int index=0;index<wn;index++)
{
hcd[index]="";
p=ht[index];
while(p.parent!=null)
{
if(p.flag)
{
hcd[index]+='0';
}
else
{
hcd[index]+='1';
}
p=p.parent;
}
hcd[index]=reverse(hcd[index]);
}
return p;
}
public static String reverse(String s)
{
String t="";
for(int index1=s.length()-1;index1>=0;index1--)
{
t+=s.charAt(index1);
}
return t;
}
public static void showCode()
{
for(int index=0;index<wn;index++)
{
System.out.println(ht[index].data+" "+hcd[index]);
}
}
public static void transformtostring(HTNode root)
{
if(root==null) return;
else
{
transformtostring(root.lchild);
transformtostring(root.rchild);
if(root.data<=122&&root.data>=97)
{
System.out.println("data:"+root.data+" weight:"+root.weight);
}
}
}
}
数据结构:哈夫曼节点
public class HTNode {
char data;
int weight;
public HTNode parent;
HTNode lchild;
HTNode rchild;
boolean flag;
public HTNode()
{
parent=null;
lchild=null;
rchild=null;
}
public double getweight()
{
return weight;
}
}
``
测试类
```java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Huffman tree=new Huffman();
tree.str="abcdefgh";
tree.wn=8;
int[] w= {7,19,2,6,32,3,21,10};
tree.init(tree.wn, w, tree.str);
tree.createHT();
HTNode root=tree.transfromtoCode();
tree.showCode();
tree.transformtostring(root);
}
}