简体   繁体   中英

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 be 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM