我正在尝试编写一个霍夫曼解码算法。我决定采用迭代方法。我相信我遇到的主要问题与我的nodetype结构有关。在DDD中,它说没有正确的*孩子。有关为什么会这样的建议吗?我已经搜遍了所有问题并没有找到解决方法。有什么建议吗?
为简单起见,我省略了程序的其余部分。
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
#include <sstream>
using namespace std;
typedef unsigned int uint;
struct nodetype
{
// constructor
nodetype( char symbol, nodetype * left, nodetype * right) :
symbol( symbol ), left( left ), right( right )
{ }
char symbol;
nodetype* left;
nodetype* right;
};
void createDecodingTree( nodetype* root,
nodetype* &iter,
string &codeSubstring,
char leaf )
{
string code = codeSubstring;
nodetype* newLeaf = new nodetype( leaf, NULL, NULL );
uint index = 0;
uint codeLength = code.length();
iter = root;
//traverse through the code until the second to last bit
//for( uint i = 0; i <= code.length()-1; i++ );
while( codeLength - 1 > 0 )
{
if( code.at(index) == '0' )
{
if( iter->left == NULL )
{
nodetype* newLeft = new nodetype( '\0', NULL, NULL );
iter->left = newLeft;
iter = iter->left;
}
else{
iter = iter->left;
}
}
if( code.at(index) == '1' )
{
if( iter->right == NULL )
{
nodetype* newRight = new nodetype( '\0', NULL, NULL );
iter->right = newRight;
iter = iter->right;
}
else{
iter = iter->right;
}
}
codeLength--;
index++;
}
//now make a new leaf based on the last bit
if( code.at( code.length() - 1 ) == '0' )
iter->left = newLeaf;
else{
iter->right = newLeaf;
}
}
这就是我初始化root的方式。
nodetype* root = new nodetype( '\0', NULL, NULL );