开发者

Huffman Encoding Algorithm giving strange tree (Java)

I've been trying a lot of different things here and can't seem to get it to work. The input was "abbcccddddeeeee", which gives a linked list a, b, c, d, e with frequencies 1, 2, 3, 4, 5, respectively.

For some reason, though, it appears to b开发者_开发百科e giving me the following tree based on a lot of different tests I've run:

                  f15
                 /   \
                f6   f9
               /  \
              d4  e5
             /  \
           f3    c3
          /  \
         a1  b2

public static HTree createHuffmanTree(HLinkedList list)
{
    while (list.size() != 1)
    {
    list = getSortedLinkedList(list);
    HTreeNode p = list.head;
    HTreeNode q = p.next;
    HTreeNode r = new HTreeNode('f');
    r.left = p;
    r.right = q;
    r.frequency = (p.frequency + q.frequency);
    list.insertIntoPosition(r, 2);
    list.remove(0);
    list.remove(0);
    list = getSortedLinkedList(list);
    }
    return new HTree(list.head);
} 

It would be absolutely amazing if someone could help me out, I'm incredibly, incredibly frustrated.

Thank you!


The problem is in getSortedLinkedList. It appears that you are swapping frequency values and not the nodes themselves so the pointers aren't being moved with the frequency value.

Generally, when you're dealing with linked lists it's really useful to draw pictures of each stage:

 a1->b2->c3->d4->e5

first step:

  f3->c3->d4->e5
  /\
a1  b2

sort: no change

next step:

    f6->d4->e5
    /\
  f3  c3
  /\
a1  b2

sort does this:

    d4->e5->f6 (forgot to move child nodes with frequency)
    /\
  f3  c3
  /\
a1  b2

next step:

      f9->f6
      /\
    d4  e5
    /\
  f3  c3
  /\
a1  b2

sort:

      f6->f9 (forgetting to move child nodes with frequency)
      /\
    d4  e5
    /\
  f3  c3
  /\
a1  b2

final step:

             f15
             /\
           f6  f9
           /\
         d4  e5
         /\
       f3  c3
       /\
     a1  b2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜