
struct Node {
UINT key; // 字元值
UINT frequency; // 權重
Node *_left, *_right;
Node(): key(EMPTY), frequency(0), _left(NULL), _right(NULL) {}
};
typedef Node* PNode;
class PriorityQueue {
PNode table[256]; // 固定 256 字元集
UINT heapSize;
// Min-Heap 操作: build, insert, extractMin, minHeapify, swap
};
PriorityQueue::PriorityQueue(char *data, int len) {
for (int i = 0; i < len; ++i) {
bool found = false;
for (int j = 0; j < heapSize; ++j)
if (table[j]->key == data[i]) {
table[j]->frequency++;
found = true; break;
}
if (!found) {
table[heapSize]->key = data[i];
table[heapSize]->frequency = 1;
heapSize++;
}
}
heapSize--;
buildMinHeap(heapSize);
}
PNode BuildHuffmanTree(PriorityQueue &q) {
PNode parent, left, right;
while (q.heapSize != EMPTY) {
left = new Node; right = new Node; parent = new Node;
copyNode(q.extractMin(), left);
copyNode(q.extractMin(), right);
parent->frequency = left->frequency + right->frequency;
parent->_left = left; parent->_right = right;
if (q.heapSize == EMPTY) break;
q.insert(parent);
}
return parent;
}
void showCode(PNode root, vector &code) {
if (!root) return;
if (!root->_left && !root->_right) { // 葉節點
cout << (char)root->key << " code: ";
for (char bit : code) cout << (int)bit;
cout << endl;
return;
}
code.push_back(0); showCode(root->_left, code);
code.back() = 1; showCode(root->_right, code);
code.pop_back();
}
輸入:"xxznxznnvvccncvzzbzzvxxczbzvmnzvnnz"

霍夫曼編碼雖最優,但錯誤傳播性強:1 bit 錯誤導致後續解碼全錯。實務常配合同步標記或分塊獨立編碼緩解。