好的,以下是仅输出最优二元树权重的代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct HuffmanNode {
int weight;
HuffmanNode* left, * right;
HuffmanNode(int leaf) : weight(leaf), left(nullptr), right(nullptr) {}
};
struct Compare {
bool operator()(HuffmanNode* l, HuffmanNode* r) {
return l->weight > r->weight;
}
};
int calculateWPL(vector<int>& tree) {
priority_queue<int, vector<int>, greater<int>> pq(tree.begin(), tree.end());
while (pq.size() > 1) {
int left = pq.top();
pq.pop();
int right = pq.top();
pq.pop();
int combined = left + right;
pq.push(combined);
}
return pq.top();
}
int main() {
vector<int> tree = {1, 3, 4, 5, 6};
int wpl = calculateWPL(tree);
cout << "最优二元树的权: " << wpl << endl;
return 0;
}
这段代码简化了哈夫曼树的构建过程,并直接计算并输出最优二元树的权重。
内容由零声教学AI助手提供,问题来源于学员提问




