【问题标题】:Trouble with getting codes for Huffman Tree获取霍夫曼树代码的问题
【发布时间】:2015-04-18 00:55:15
【问题描述】:

我需要创建代码来压缩霍夫曼树。 (O 如果你向左遍历 1 如果你向右遍历。)

现在codes数组会得到正确的第一个code,但之后只会返回null。

我不允许使用任何instance/global 变量或除array 和arrayList 之外的任何预定义java 类

public static String compress(final BinaryNodeInterface<Character> root, final String message)
{
    String[] codes;
    ArrayList<Character> letter = new ArrayList<Character>();
    String codeString = "";
    boolean addChar=true;

    for(int i =0; i<message.length();i++)
    {
        for(int j=0;j<letter.size();j++)
            if(message.charAt(i)==letter.get(j))
                addChar=false;
            else
                addChar=true;
        if(addChar)               
            letter.add(message.charAt(i));
    }

    codes = new String[letter.size()];
    for(int i=0;i<letter.size();i++)
        codes[i]=(getPath(root,letter.get(i),""));

    return "";  // Do not forget to change this line!!!
}

private static String getPath(final BinaryNodeInterface<Character> root, char toFind, String path)
{
    String result;
    if (! root.isLeaf()) {
        if ((result = getPath(root.getLeftChild(),toFind, path + '0')) == null) {
            result = getPath(root.getLeftChild(),toFind, path + '1');
        }
    }
    else {
        result = (toFind == root.getData()) ? path : null;
    }
    return result;
}

【问题讨论】:

    标签: recursion tree binary-tree huffman-code


    【解决方案1】:

    您似乎没有访问正确的子孩子。改变

    result = getPath(root.getLeftChild(),toFind, path + '1');
    

    result = getPath(root.getRightChild(),toFind, path + '1');
    

    【讨论】:

    • 谢谢,这是我迄今为止犯的第二个愚蠢的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多