我已经创建了霍夫曼树,但我在生成代码时遇到了问题

时间:2013-03-18 09:33:06

标签: java huffman-code

这是我的函数,我用树的根节点和树中找到的字符来播种它。它成功地返回了我要搜索的字母,但它没有给我元素的路径。我有点卡住任何帮助都会被扼杀

public Node traversingTree(Node root,String charToFind){

    Node tempRoot = root;

    if (root != null){

        if (charToFind.equals(root.getAlphabet()))
        {
            //Another Point of consideration
            System.out.print(root.getAlphabet());
            System.out.println(": "+pathCodes);
            pathCodes.clear();
            return root;
        }
        Node result;

        if ((result = traversingTree(root.leftChild, charToFind)) != null){

            pathCodes.add("0");
            return result;

        }else
            pathCodes.add("1");
            return traversingTree(root.rightChild, charToFind); 
        }

        }
    pathCodes.clear();

     return null;

}

1 个答案:

答案 0 :(得分:1)

你没有确切地说出你做什么得到了什么,但是看着你的代码,你的右手递归就是在继续向前看之前添加'1'为适当的节点。但是,您清除叶子节点上的代码,这将在添加所有“1”之后发生。所以我希望你的代码只包含'0',因为在递归之后'0'会附加

此外,我怀疑当您在返回向上树的路上添加字符时,代码将返回到前面。

在重新考虑你的递归时,无论如何我会建议使用这样的huffman树。搜索代码是非常低效的 - 我建议遍历树一次,构建一个字母表+代码表,然后简单地索引到那个。

最好只使用树来计算代码长度,并使用规范编码生成代码。