2012-11-06 41 views
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是保存字符值,字符和編碼的概率自定義類。

它在我用箭頭指示的行if (t.getLeft().getData().getCharacter() == character) {處不斷返回一個NullPointerExceptionError。我嘗試過,但我似乎無法弄清楚爲什麼,除了事實上,它是返回錯誤,而不是整個事件,或t.getLeft(),但我仍然無法弄清楚爲什麼。

+0

首先使用您的調試器進入'getData()',並找出它爲什麼在您不期望時返回'null'。 –

+2

發現錯誤的問題可能是尋找錯誤位置的問題。引用的代碼依賴於樹節點始終具有非空數據,因此如果t.getRight()不爲null,則t.getRight()。getData()也不會。也許樹木建築出錯了。 –

回答

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

p.s.如果您要返回0 s和1 s的位串,並且避免每次在findCharEncoding處設置樹節點的編碼,那麼您也可以避免返回「-1」,但這只是一個瘋狂的猜測。 :)

相關問題