2

My Huffman algorithm is working until I have to generate code for each symbol in tree. I don't know what is wrong. So when I start program it generates code for each Node, but does not append code from father.


Example:

How it looks like

     null
    0     1
  0  1   0 1

what it should look like:

    null
  0      1
00 01  10 11

Node class:

public class Node
{
    public int teza = 0;
    public int znak = 0;
    public string code= "";
    public Vozlisce father= null;
    public Vozlisce left= null;
    public Vozlisce right= null;
}

Code:

List<Node> tree= new List<Node>();
while(pravi.Count > 0)
{
    if(pravi.Count == 2)
    {
        Node root = new Node();
        root.right = pravi.Last();
        pravi.Last().father = root;
        root.teza += pravi.Last().teza;
        pravi.RemoveAt(pravi.Count - 1);

        root.left= pravi.Last();
        pravi.Last().father = root;
        root.teza += pravi.Last().teza;
        pravi.RemoveAt(pravi.Count - 1);

        root.left.code = root.code + 0;
        root.right.code = root.code + 1;

        tree.Add(root);
        break;
    }

    Node father = new Node();
    father.right = pravi.Last();
    pravi.Last().father = father;
    father.teza += pravi.Last().teza;
    pravi.RemoveAt(pravi.Count - 1);

    father.left = pravi.Last();
    pravi.Last().father = father;
    father.teza += pravi.Last().teza;
    pravi.RemoveAt(pravi.Count - 1);

    father.left.code = father.code+ 0;
    father.right.code = father.code+ 1;

    pravi.Add(father);
}
EpicKip
  • 4,015
  • 1
  • 20
  • 37
lucian24
  • 45
  • 6
  • 2
    In your `if` statement you are setting `root.code + n`, but root.code is always an empty string because it's the initial value of the newly created object. Actually, the `father` part does the same – bixarrio May 17 '17 at 14:04
  • Oh now I see thanks – lucian24 May 17 '17 at 14:06

0 Answers0