我想從二叉搜索樹中構建一個哈夫曼樹。可悲的是我的代碼崩潰(分段錯誤(核心轉儲))。從二分搜索樹構建哈夫曼樹
這是怎麼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;
}
編輯:增加了對代碼功能通過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);
}
}
使用調試器或插入'puts()'調用來確定故障發生的確切位置。然後跟蹤相關邏輯並找出問題所在。 – Downvoter
段落違例的可能候選者是'while(root-> m_ch)...':從樹中刪除最後一個節點後,'root'爲'NULL',不能用' - >'' 。所以只是'while(root)'應該沒問題。 –
如果'root'是一個節點,使得'current-> m_ls!= NULL'和'current-> m_ch == 0',delMin()'的while循環立即退出。由於'current-> m_ch == 0',測試進入並且'b4Current-> m_ls = NULL;'被執行。但'b4Current'未被初始化:可觸發分段故障。 – francis