[英]Building Huffman encoding tree from ordered list
我正在從頻率最低的有序鏈表(按字母頻率排序)構建霍夫曼編碼樹。 創建樹后,我遍歷了它,似乎樹的實現不正確。 當我遍歷樹時,有序鏈接列表中的某些節點似乎已被忽略。 (我不認為這是因為遍歷是錯誤的。)這是樹的代碼:
//My class for the nodes in the ordered linked list that will be converted to a tree
class fList{
public:
fList();
int frequency;
char letter;
fList* next;
fList* left;
fList* right;
};
fList::fList(){
frequency = 0;
letter = NULL;
next = NULL;
left = NULL;
right = NULL;
}
fList* head = NULL;
.
.
.
.
.
//Create the huffman encoding tree from the linked list stored in head
while(head->next != NULL){
fList *tree = new fList();
fList *temp = new fList();
fList *trail = new fList();
/* Take the first two frequency numbers, add them, create a new node
* with the total frequency number and have new node point to the first
* two nodes (right child and left child)
*/
total = (head->frequency + head->next->frequency);
tree->frequency = total;
//Set a new head node
tree->left = head;
tree->right = head->next;
head = head->next->next;
tree->left->next = NULL;
tree->right->next = NULL;
//place tree node in its correct place in sorted list
temp = head;
trail = temp;
if(head->frequency >= tree->frequency){
tree->next = head;
head = tree;
}
else if(temp->next != NULL){
while(temp != NULL){
if(temp->frequency >= tree->frequency){
tree->next = temp;
trail->next = tree;
break;
}
else{
trail = temp;
temp = temp->next;
}
}//while
//insert at the end of list
if(temp == NULL){
temp = tree->next;
trail->next = tree;
}
}//else if !=NULL
else if(head == NULL || head->next == NULL) head = tree;
}
在您發布的代碼段的最后一行
else if(temp->next = NULL && head != NULL) head = tree;
您無意間通過設置temp->next = NULL
截斷樹,您可能想詢問是否temp->next == NULL
。 這可能就是為什么某些條目(由temp
鏈接的條目)被排除在最終結果之外的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.