簡體   English   中英

使用樹進行霍夫曼解碼的問題

[英]issues with huffman decoding using tree

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

所以我的代碼:

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

節點只是擁有值並具有左右指針的東西。

這里出了什么問題,但是我不確定這到底是什么。 有人看到實施中有任何明顯的問題嗎?

編輯:嗯,我發現了一些有趣的東西。 似乎每讀取一次,它就會一直到找到葉子為止。 我想這就是我的編碼方式。 例如,當讀取“ 1”時,它會正確,再次正確地顯示“ d”。 遞歸:(

一個問題是-在buildTree ,如果當前節點已經有一個子節點怎么辦? 您將只創建一個新子項並覆蓋前一個子項。

如果節點還沒有子節點,則只應創建該節點。

因此,您的buildTree函數應如下所示:

void Foo:: buildTree(vector<char> v) {
        node* root = new node; 
        vector<char>:: iterator itr;
        node* current = root; 

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

            if (*itr == '0') {
                if (current->left == NULL)
                   current->left = new node;
                current = current->left;
            }
            else if (*itr == '1') {
                if (current->right == NULL)
                   current->right = new node;
                current = current->right;
            }
            else {  // is a symbol
                current->value = *itr; 
                current = root; 
            }
        }
        nodeVector.push_back(*root); 
}

另一個問題是您的decode功能-您要遍歷樹,但要傳遞相同的bit

我可能會完全放棄遞歸方法,而只使用一個for循環。

一些偽代碼:

current = root
for each character c
  if c == 0
    if current.left == NULL
      print current.value
      current = root
    else
      current = current.left
  else
    if current.right == NULL
      print current.value
      current = root
    else
      current = current.right

您需要將 bit傳遞給decode的遞歸,而不是當前位。 實際上,您無需遞歸即可執行操作,只需從decode返回新的tempRoot並繼續進行迭代即可。 解碼葉節點時,請不要忘記返回root

順便說一句: buildTree很多內存泄漏。

暫無
暫無

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

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