建立一个霍夫曼树

时间:2010-07-23 00:14:20

标签: java tree huffman-code

我一直在研究这个霍夫曼树的建设者:

// 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(包含所有字符)的大小,将前两个队列出列,然后设置一个新的root,使得一个左右子节点成为2个节点的队列,然后插入新的根节点,其中2个队列的组合频率出列项目进入优先级队列。这就是所有方法都应该做的。

这个方法应该构建Huffman树,但它正在构建错误我已经按照代码并手工构建了树,但我在纸上得到的与程序不同!由不同程序生成的正确答案与我的解决方案不同。输入数据(字母和频率)是:

a 6
b 5
space 5
c 4
d 3
e 2
f 1

至于我从中读取的文本并不重要,因为频率已经在这里。我需要做的就是从这些频率构建树。

2 个答案:

答案 0 :(得分:2)

您是否可以尝试用简单的语言写出算法,忽略任何Java细节?这可能有助于您了解出现问题的地方(无论是在算法中还是在实现它的代码中),还可以帮助人们帮助您。

无论算法如何,您真的打算让您的根节点从ArrayList中的第二个元素开始吗? List的索引从0开始,而不是1. List.get(1)返回第二个元素。

public Frequency buildTree(ArrayList<Frequency> al) {
    Frequency r = al.get(1);

答案 1 :(得分:0)

什么时候到期?我将开始为您的实现的每个功能位编写单元测试 - 您可能能够以这种方式公开您的问题。还要修复您的格式 为了这个烂摊子

“public Frequency buildTree(ArrayList al){Frequency r = al.get(1); PriorityQueue pq = new PriorityQueue(); for(int i = 0; i&lt; al.size(); i ++){pq 。新增(al.get(I)); } / while(pq.size()&gt; 0){System.out.println(pq.remove()。getString()); } /“

编辑 - 格式化后 - 我很难读你的代码。使变量名称具有描述性。 'r'没有告诉我什么,也没有告诉我'al'。知道您编码的文本是什么有帮助....