霍夫曼树节点不会将代码附加到他的儿子

时间:2017-05-17 13:54:58

标签: c# string algorithm huffman-code

我的霍夫曼算法正在工作,直到我必须为树中的每个符号生成代码。我不知道出了什么问题。因此,当我启动程序时,它会为每个Node生成代码,但不会附加父代码。

示例:

它看起来如何

     null
    0     1
  0  1   0 1

应该是什么样的:

    null
  0      1
00 01  10 11

节点类:

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;
}

代码:

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);
}

0 个答案:

没有答案