哈夫曼树python实现
时间: 2024-03-25 19:34:56 浏览: 135
哈夫曼树的实现.pdf
哈夫曼树是一种用于数据压缩的树形结构,它通过将出现频率较高的字符用较短的编码表示,从而实现数据的高效压缩。下面是哈夫曼树的Python实现示例:
```python
class Node:
def __init__(self, freq, char=None):
self.freq = freq
self.char = char
self.left = None
self.right = None
def build_huffman_tree(data):
# 统计字符频率
freq_map = {}
for char in data:
if char in freq_map:
freq_map[char] += 1
else:
freq_map[char] = 1
# 构建叶子节点列表
nodes = []
for char, freq in freq_map.items():
nodes.append(Node(freq, char))
# 构建哈夫曼树
while len(nodes) > 1:
nodes.sort(key=lambda x: x.freq)
left = nodes.pop(0)
right = nodes.pop(0)
parent = Node(left.freq + right.freq)
parent.left = left
parent.right = right
nodes.append(parent)
return nodes[0]
def encode_huffman_tree(root, prefix="", code_map={}):
if root.char is not None:
code_map[root.char] = prefix
else:
encode_huffman_tree(root.left, prefix + "0", code_map)
encode_huffman_tree(root.right, prefix + "1", code_map)
return code_map
def huffman_encoding(data):
root = build_huffman_tree(data)
code_map = encode_huffman_tree(root)
encoded_data = ""
for char in data:
encoded_data += code_map[char]
return encoded_data, root
def huffman_decoding(encoded_data, root):
decoded_data = ""
current_node = root
for bit in encoded_data:
if bit == "0":
current_node = current_node.left
else:
current_node = current_node.right
if current_node.char is not None:
decoded_data += current_node.char
current_node = root
return decoded_data
```
以上是一个简单的哈夫曼树的Python实现。你可以使用`huffman_encoding`函数对数据进行编码,使用`huffman_decoding`函数对编码后的数据进行解码。
阅读全文