簡體   English   中英

霍夫曼解碼樹的奇怪錯誤

[英]strange bug with huffman decoding tree

我較早時提出了有關算法和實現的問題,但遇到了我無法解決的問題。

我能夠從文本文件中提取前綴並將其放入向量中,例如:

a 0
b 100
c 101
d 11

[0, a, 1, 0, 0, b, 1, 0, 1, c, 1, 1, d]

所以我的代碼:

  • 從根節點開始
  • 遍歷向量。 如果我們得到0,則取當前節點,並使其左指針指向新節點。 如果得到1,則取當前節點,並使其正確的指針指向新節點。 如果是字母,則將該字符存儲到當前節點並從根開始。

(一個節點僅持有一個值,並具有左右指針)

void Foo:: build(vector<char> v) {
    node* root = new node; 

    vector<char>:: iterator itr;

    node* current = root; 
    cout << " *" << endl;

    for(itr =  v.begin(); itr != v.end(); itr++) {
        cout << "(" << *itr << ")" << endl;

        if (!isdigit(*itr)) {
            current->value = *itr; 
            current = root; 
            cout << "*" << endl;
        }
        if (*itr == '0') {
            cout << "<-" << endl; 
            current->left = new node; 
            current = current->left; 
        }
        if (*itr == '1') {
            cout << "->" << endl; 
            current->right = new node; 
            current = current->right; 
        }
    }

    nodeVector.push_back(*root); 
}

如果您對couts感到好奇,則*表示根。 因此對於'a',它將從根*開始,遇到0,然后<-左移以將'a'放入該節點,然后從根*開始。 我只是這樣做,看它是否像應該的那樣向左和向右運動,這似乎還可以。

 *
(0)
<-
(a)
*
(1)
->
(0)
<-
(0)
<-
(b)
*
(1)
->
(0)
<-
(1)
->
(c)
*
(1)
->
(1)
->
(d)
*

我遇到的問題很奇怪。 似乎唯一起作用的字母是“ a”和“ d”。 例如, root->left->value會給我“一個”, root->right->right->value將給予“d”,但root->right->left->right->value應為'c'似乎從來沒有放在節點位置。 當我嘗試獲取此值時,程序崩潰。 當我嘗試對一串位進行解碼時,該消息是錯誤的,因為它只能執行“ d”和“ a”。 這使我懷疑這是樹的建造。 任何建議將不勝感激!

在分配新節點之前,您需要檢查該路徑之前是否已經分配過。 例如

if (*itr == '0') {
    cout << "<-" << endl;
    if (current->left) current = current->left;
                  else current = (current->left = new node);
}

6502是正確的。

每次您的傳遞循環通過時,您都在樹上構造一條新路徑 左邊的一個很好,因為它永遠不會被覆蓋(但是如果您有一個節點和2個葉子而不是一個葉子,它也會失敗)。 每次都會重新分配右側的路徑,並且該路徑會覆蓋之前創建的節點,因此只有您最后的“ d”條目可見。 換句話說,創建了“ b”和“ c”,但是每次創建新的正確條目時,指向它們的指針都會丟失(覆蓋)。

正如6502指出的那樣,您需要檢查是否已創建該節點。 但是您的代碼可能會失敗,因為空指針未初始化為0,因此代碼就像節點已存在一樣繼續進行,但實際上並沒有。 每一個 new node 必須初始化空指針, leftright ,如果你打算測試它們的內容。 例如:

if (*itr == '0') {
    cout << "<-" << endl;
    if (current->left) current = current->left;
    else
    {
        current = (current->left = new node);
        current->left = 0;  // initialize your empty pointers!
        current=>right = 0; // initialize your empty pointers!
    }
}

注意,在new構造函數中放置指針初始化的更好的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM