> 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-coding.md).

# 哈夫曼编码

### 什么是哈夫曼编码

一种**前缀编码**（任一编码都不是另一编码的前缀），且平均码长最短，用于数据压缩。

### 构造步骤

1. 统计每个字符的出现频率（作为权值）；
2. 构造哈夫曼树（频率小的在深层）；
3. 左分支标 0，右分支标 1；
4. 从根到叶子的路径 0/1 序列即为该字符的编码。

### 示例

字符频率：A:5，B:2，C:1，D:3。

按哈夫曼构造后可能的编码：A=0，D=11，C=100，B=101。

### 前缀性质

因为字符都对应叶子结点，路径不会互相包含，所以不会出现“一个编码是另一个前缀”的歧义，解码唯一。

### 与哈夫曼树的关系

哈夫曼编码的平均码长 = 哈夫曼树的 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-coding.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.
