霍夫曼码树解码

时间:2018-04-02 20:51:25

标签: java huffman-code

我尝试解码huffmann二进制代码树但没有成功。我使用以下代码:

public static int decodeTree(String str){
    int length = str.length();
    int num = 0;
    int number = 0;
    Node root = tree1.get(0);
    String b;
    // 0 left
    // 1 right
    for (int x = 0; x <tree1.size(); x++) {
      Node curr = root;
      while ((curr.isLeaf() == false) && num < length) {
        if (str.charAt(num) == '0') {
          curr = curr.Left();
          num++;
        }
        else if (str.charAt(num) == '1') { 
          curr = curr.Right();
          num++;
        }
      }

      number = curr.getValue();
    }

    return number;
}

应输出:

10, 46, 200, 155, 50, 50, 23, 12, 18, 59, 40, 10, 200, 10, 40, 50, 46, 12, 18, 200, 46

目前正在输出:

155, 46, 200, 200, 50, 91, 23, 12, 46, 200, 40, 200, 155, 50, 200, 68, 38, 50, 18, 200, 200

返回十进制数。它正确地解码了一些数字,但序列错误。你知道可能出现什么问题吗?

我还上传了我的Tree实现:

public static String[] huffman(int[] histo){
    //initial list of nodes
        tree1 = new ArrayList<>();
    for (int i = 0; i < histo.length; i++)
        if(histo[i] != 0) {
            tree1.add(new Node(histo[i], i));
        }

    //get weights until only root node is left out
    while(tree1.size() > 1){
        combine(tree1);
    }

    //recursively generate code for each node in the tree
    //if the recursion finds a leaf node,
    //it sets the correct element in the array to the code of the node
    Node root = tree1.get(0);
    String[] codage = new String[histo.length];
    root.genCodeWord(codage);

    return codage;
}

更多信息:

这就是我尝试解码的方式:

String[] oneDConvertedBack1 = new String[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++)
    Gray graycode = new Gray();
    oneDConvertedBack1[i] = graycode.convertToBinaryCode(oneDGray[i]);
}
for(int i=0; i<oneD.length;i++)
    System.out.print(oneDConvertedBack1[i]+ ", ");

int[] oneDConvertedBack2 = new int[oneD.length];
System.out.print("\n\nCONVERTED BACK:\n");
for(int i =0; i<oneD.length; i++) {
    oneDConvertedBack2[i] = decodeTree(oneDBinary[i]);
}

以下是树节点及其CodeWord方法的组成部分

public Node(Node left, Node right, int value){
    l = left;
    r = right;
    v = value;
    i = -1;
}

public void genCodeWord(String[] codes){

    if(l != null && r != null){
        l.setCodeWord("0"+getCodeWord());
        l.genCodeWord(codes);
        r.setCodeWord("1"+getCodeWord());
        r.genCodeWord(codes);
    }else{
        codes[i] = getCodeWord();
    }
}

0 个答案:

没有答案