[英]issues with huffman decoding using tree
我能夠從文本文件中提取前綴並將其放入向量中,例如:
所以我的代碼:
節點只是擁有值並具有左右指針的東西。
這里出了什么問題,但是我不確定這到底是什么。 有人看到實施中有任何明顯的問題嗎?
編輯:嗯,我發現了一些有趣的東西。 似乎每讀取一次,它就會一直到找到葉子為止。 我想這就是我的編碼方式。 例如,當讀取“ 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.