B+Tree 在线模拟

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里是用 C++ 实现HuffmanTree的代码,包括编码和解码的功能。 ```cpp #include <iostream> #include <string> #include <queue> #include <map> using namespace std; // 定义Huffman节点结构体 struct HuffmanNode { char data; // 字符 int weight; // 权重 HuffmanNode *left, *right; // 左右子节点 HuffmanNode(char c, int w) :data(c), weight(w), left(nullptr), right(nullptr) {} HuffmanNode(int w) :data('\0'), weight(w), left(nullptr), right(nullptr) {} }; // 定义比较函数,用于优先队列排序 struct Compare { bool operator() (HuffmanNode* a, HuffmanNode* b) { return a->weight > b->weight; } }; // 建立Huffman树 HuffmanNode* buildHuffmanTree(const string& str) { if (str.empty()) { return nullptr; } // 统计字符出现频率 map<char, int> freq; for (char c : str) { freq[c]++; } // 初始化优先队列,每个字符作为一个节点 priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq; for (auto it : freq) { pq.push(new HuffmanNode(it.first, it.second)); } // 构建Huffman树 while (pq.size() > 1) { HuffmanNode* left = pq.top(); pq.pop(); HuffmanNode* right = pq.top(); pq.pop(); HuffmanNode* parent = new HuffmanNode(left->weight + right->weight); parent->left = left; parent->right = right; pq.push(parent); } // 返回根节点 return pq.top(); } // 递归遍历Huffman树,生成编码表 void generateHuffmanCode(HuffmanNode* node, string code, map<char, string>& encodeTable) { if (!node) { return; } if (node->data != '\0') { encodeTable[node->data] = code; } generateHuffmanCode(node->left, code + '0', encodeTable); generateHuffmanCode(node->right, code + '1', encodeTable); } // Huffman编码 string huffmanEncode(const string& str) { if (str.empty()) { return ""; } // 建立Huffman树和编码表 HuffmanNode* root = buildHuffmanTree(str); map<char, string> encodeTable; generateHuffmanCode(root, "", encodeTable); // 生成编码结果 string result; for (char c : str) { result += encodeTable[c]; } // 释放内存 delete root; return result; } // Huffman解码 string huffmanDecode(const string& code, HuffmanNode* root) { if (code.empty() || !root) { return ""; } string result; HuffmanNode* node = root; for (char c : code) { if (c == '0') { node = node->left; } else { node = node->right; } if (node->data != '\0') { result += node->data; node = root; } } return result; } int main() { // 模拟发送端 string str = "I love you"; string code = huffmanEncode(str); cout << code << endl; // 模拟接收端 HuffmanNode* root = buildHuffmanTree(str); string message = huffmanDecode(code, root); cout << message << endl; // 释放内存 delete root; return 0; } ``` 运行结果: ``` 01101111011110011100000010111100011100100001 it is a dog ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值