从二叉搜索树构建霍夫曼树

时间:2015-05-14 13:32:44

标签: c binary-tree binary-search-tree huffman-code

我正在尝试用二叉搜索树构建一个霍夫曼树。可悲的是我的代码崩溃了(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);
  }
}

1 个答案:

答案 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 == 0m_ls == NULL的情况。您将使用if分支并取消引用b4Current

您需要使用b4Current初始化NULL并在取消引用之前检查它。

在初始化root中的current = *rootdelMin

中取消引用之前,您还需要确保huffman本身不为空

这些都应该初始化为NULL

struct Node *left;
struct Node *right;
struct Node *tempRoot;
struct Node *huffmanTree;

并且有可能再次永远不会进入while循环,而tempRoot取消设置会在返回其值时在huffman的调用者中导致潜在的segFault。