簡體   English   中英

解碼霍夫曼樹

[英]Decoding a Huffman Tree

我正在嘗試解碼以下形式的霍夫曼樹:

001A1C01E01B1D

我正在使用一種在這里找到的實現: 一種存儲霍夫曼樹的有效方法,以上述形式對進行編碼並對其進行解碼。

這是我的實現:

HuffmanNode* HuffmanTree::decodeTree(string tree, int idx) {
    cout << idx << endl;
    if (tree[idx] == '1') {
        idx += 2;
        return new HuffmanNode(tree[idx - 1]);
    }
    else {
        if (idx != tree.length() - 1) {
            idx++;
            HuffmanNode* leftChild = decodeTree(tree, idx);
            idx++;
            HuffmanNode* rightChild = decodeTree(tree, idx);
            return new HuffmanNode(leftChild, rightChild);
        }
        else
            return new HuffmanNode(tree[idx]);
    }
}

當函數展開時,我遇到寫訪問位置的訪問沖突(在“ return new HuffmanNode(tree [idx-1]);”上),我希望最終的返回將是樹的根,但是經進一步檢查似乎並非如此。 誰能給我一些指導? (無雙關語)

您的代碼的問題在於,遞歸運行中不會修改idx 將其作為int &傳遞給函數HuffmanNode* HuffmanTree::decodeTree(string tree, int &idx)

您的代碼中還有一個bug,這使其成為segfault:

if (tree[idx] == '1') {
    idx += 2;
    return new HuffmanNode(tree[idx - 1]);
}

你應該有

if (tree[idx] == '1') {
    ++idx;
    return new HuffmanNode(tree[idx]);
}

第二個塊中的索引被添加了另一個1

idx++;
HuffmanNode* leftChild = decodeTree(tree, idx);
idx++;
HuffmanNode* rightChild = decodeTree(tree, idx);

另外,考慮做一件事情,類似於您鏈接到的示例:將引用傳遞給字符串迭代器(或istringstream或其他流),並且不要傳遞索引: HuffmanNode* HuffmanTree::decodeTree(std::string::const_iterator &tree)

另外,如果樹的格式正確,則不必進行if (idx != tree.length() - 1)類的檢查。 您仍可以在函數開始時執行此操作,以檢查輸入中的錯誤以及檢查當前符號為'0''1'

暫無
暫無

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

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