> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/data-structures/huffman-tree.md).

# 哈夫曼树

### 带权路径长度

* 结点的**路径长度**：从根到该结点经过的边数
* 树的**带权路径长度 WPL**：所有叶子结点的（权值 × 路径长度）之和
* **哈夫曼树**：WPL 最小的二叉树，又称最优二叉树

### 构造方法（贪心）

1. 把所有结点放入集合；
2. 每次取出**权值最小的两个**结点，合并成新结点（权值 = 两者之和），放回集合；
3. 重复直到只剩一个结点，即为哈夫曼树的根。

### 示例

权值 1、2、3、4：

```
取 1,2 合并为 3  → {3,3,4}
取 3,3 合并为 6  → {4,6}
取 4,6 合并为 10 → 根为 10
WPL = 1×3 + 2×3 + 3×2 + 4×1 = 19
```

### 优先队列实现

```cpp
priority_queue<int, vector<int>, greater<int>> pq; // 小根堆
for (int i = 0; i < n; i++) pq.push(w[i]);
int ans = 0;
while (pq.size() > 1) {
    int a = pq.top(); pq.pop();
    int b = pq.top(); pq.pop();
    ans += a + b;
    pq.push(a + b);
}
cout << ans << endl;  // 最小 WPL
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/data-structures/huffman-tree.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
