有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Huffman代码树解码

我试图破解哈夫曼二进制代码树,但没有成功。我使用以下代码:

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

它是返回十进制数。它正确地解码了一些数字,但顺序错误。你知道怎么回事吗

我还上传了我的树实现:

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

下面是树的节点及其码字方法的组成部分

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) 个答案