0

我有一个霍夫曼树和一个字符,我想返回该字符在霍夫曼树中的编码应该是什么。

我已经使用广度优先遍历方法实现了它,每次检查左右树时,我都会检查树的数据是否等于我正在寻找的字符。不过,每次我向右或向左走时,我都会在编码中添加 0 或 1。最终,当我找到等于树数据的字符时,我返回该树的编码值。

代码:

    public static String findCharEncoding(BinaryTree<CharProfile> bTree, char character) {
        Queue<BinaryTree<CharProfile>> treeQueue = new LinkedList<BinaryTree<CharProfile>>();

        // Create a TreeWithEncoding object from the given arguments and add it to the queue
        treeQueue.add(bTree);

        while (!treeQueue.isEmpty()) {
            BinaryTree<CharProfile> t = treeQueue.remove();

->          if (t.getLeft().getData().getCharacter() == character) {
                return t.getLeft().getData().getEncoding();
            }
            if (t.getLeft() != null) {
                t.getLeft().getData().setEncoding(t.getLeft().getData().getEncoding() + "0");
                treeQueue.add(t.getLeft());
            }

            if (t.getRight().getData().getCharacter() == character) {
                return t.getRight().getData().getEncoding();
            }
            if (t.getRight() != null) {
                t.getRight().getData().setEncoding(t.getRight().getData().getEncoding() + "1");
                treeQueue.add(t.getRight());
            }
        }

        // If it gets to here, the while loop was unsuccessful in finding the encoding
        System.out.println("Unable to find.");
        return "-1";
    }

我已经实现如下:

        for (int i = 0; i < charOccurrences.size(); i++) {
            char character = charOccurrences.get(i).getCharacter();

            charOccurrences.get(i).setEncoding(findCharEncoding(huffmanTree, character));
            System.out.println(charOccurrences.get(i).getEncoding());
        }

CharProfile 是一个自定义类,包含字符值、字符概率和编码。

它不断在行返回 NullPointerExceptionError if (t.getLeft().getData().getCharacter() == character) {,我用箭头表示了这一点。我已经尝试过,但我似乎无法弄清楚为什么,除了t.getLeft().getData()返回错误的事实,而不是整个事情,或者t.getLeft(),但我仍然无法弄清楚为什么。

4

1 回答 1

1

如果左边或右边的树枝实际上可以是null——如果这是霍夫曼,应该只发生在叶节点上——你为什么在检查之前getData调用它们?那肯定会导致 NullPointerExeption。

if (t.getLeft() != null) {
  // check nullity and THEN check match
  if (t.getLeft().getData().getCharacter() == character) {
    return t.getLeft().getData().getEncoding();
  }
  t.getLeft().getData().setEncoding(t.getLeft().getData().getEncoding() + "0");
  treeQueue.add(t.getLeft());
}

if (t.getRight() != null) {
  if (t.getRight().getData().getCharacter() == character) {
    return t.getRight().getData().getEncoding();
  }
  t.getRight().getData().setEncoding(t.getRight().getData().getEncoding() + "1");
  treeQueue.add(t.getRight());
}

ps 如果您要返回0s 和1s 的位串,您也可能希望避免返回“-1”,并避免每次设置树节点的编码findCharEncoding,但这只是一个疯狂的猜测。:)

于 2012-11-06T04:43:53.580 回答