我一直对这个哈夫曼树构建器:构建哈夫曼树
// variable al is an array list that holds all the different characters and their frequencies
// variable r is a Frequency which is supposed to be the roots for all the leaves which holds a null string and the frequencies of the combined nodes removed from the priority queue
public Frequency buildTree(ArrayList<Frequency> al)
{
Frequency r = al.get(0);
PriorityQueue<Frequency> pq = new PriorityQueue<Frequency>();
for(int i = 0; i < al.size(); i++)
{
pq.add(al.get(i));
}
/*while(pq.size() > 0)
{
System.out.println(pq.remove().getString());
}*/
for(int i = 0; i < al.size() - 1; i++)
{
Frequency p = pq.remove();
Frequency q = pq.remove();
int temp = p.getFreq() + q.getFreq();
r = new Frequency(null, temp);
r.left = p;
r.right = q;
pq.add(r); // put in the correct place in the priority queue
}
pq.remove(); // leave the priority queue empty
return(r); // this is the root of the tree built
}
什么代码试图做英语是
与它们的频率从添加的所有字符的优先级队列最低频率最高。 接下来是ArrayList al的大小(其中包含所有字符)将第一个两个字符出列,然后设置一个新的根目录,让左右两个子节点出列,然后插入新组合的频率为2的新根将项目出队列入优先队列。那所有的方法都应该这样做。
这种方法应该是建立霍夫曼树,但它构建得不正确我遵循代码并手工构建树,但是我在纸上得到的结果与程序不同!由不同程序生成的正确答案与我的解决方案不同。输入数据(信件和频率)是:
a 6
b 5
space 5
c 4
d 3
e 2
f 1
作为该即时阅读,从它并不重要,因为频率已经在这里的文字。我所需要的2是从这些频率构建树。
大概需要看到Frequency'的'的定义以及 – barrowc 2010-07-23 00:38:38
的'定义Frequency'似乎是在您的其他问题:http://stackoverflow.com/questions/3311432/huffman-tree-encodeing – barrowc 2010-07-23 00:41:13