我正在尝试用二叉搜索树构建一个霍夫曼树。可悲的是我的代码崩溃了(Segmentation fault(core dumped))。
这是定义struct
的方式:
struct Node
{
unsigned char m_ch;
int m_freq;
struct Node *m_ls,*m_rs;
struct Node *m_hls,*m_hrs;
};
delMin
传递给二进制搜索树的双指针,并从中删除最左边的叶子,除非它到达具有m_ch==0
的节点并返回已删除的节点
我找不到我的错误
struct Node *delMin(struct Node **root)
{
struct Node *current = *root;
struct Node *b4Current;
if (current == NULL)
return NULL;
while (current->m_ls != NULL)
{
if (current->m_ch == 0)
break;
b4Current = current;
current = current->m_ls;
}
if (current->m_ch == 0)
b4Current->m_ls = NULL;
else
{
if (b4Current == NULL)
*root = current->m_rs;
else
b4Current->m_ls = current->m_rs;
}
return current;
}
struct Node *huffman(struct Node *root)
{
struct Node *left;
struct Node *right;
struct Node *tempRoot;
struct Node *huffmanTree;
while (root->m_ch != 0)
{
left = delMin(&root);
right = delMin(&root);
tempRoot = createNode((left->m_freq) + (right->m_freq), 0);
tempRoot->m_hls = left;
tempRoot->m_hrs = right;
insertTree(&root, tempRoot);
}
huffmanTree = tempRoot;
return huffmanTree;
}
编辑:为insertTree
Huffman
函数添加了代码
void insertTree(struct Node **root,struct Node *n)
{
if (!*root)
{
*root=n;
return;
}
if(n->m_freq<(*root)->m_freq)
{
insertTree(&((*root)->m_ls),n);
}
else
{
insertTree(&((*root)->m_rs),n);
}
}
答案 0 :(得分:1)
在delMin
此代码部分
if (current->m_ch == 0)
b4Current->m_ls = NULL;
else
{
if (b4Current == NULL)
*root = current->m_rs;
else
b4Current->m_ls = current->m_rs;
}
无法保证b4Current
不为NULL。
考虑根节点有m_ch == 0
和m_ls == NULL
的情况。您将使用if
分支并取消引用b4Current
。
您需要使用b4Current
初始化NULL
并在取消引用之前检查它。
在初始化root
中的current = *root
或delMin
huffman
本身不为空
这些都应该初始化为NULL
struct Node *left;
struct Node *right;
struct Node *tempRoot;
struct Node *huffmanTree;
并且有可能再次永远不会进入while循环,而tempRoot
取消设置会在返回其值时在huffman
的调用者中导致潜在的segFault。