二元哈夫曼编码的python解码代码
时间: 2024-05-06 07:13:45 浏览: 110
哈弗曼编码的编码解码
5星 · 资源好评率100%
二元哈夫曼编码是一种常用的压缩算法,它将出现频率较高的字符用较短的二进制编码表示,而将出现频率较低的字符用较长的二进制编码表示,从而减小了数据的存储空间。下面是Python中实现二元哈夫曼编码解码的代码:
```
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def decode_huffman_tree(encoded, freq):
# 构建哈夫曼树
nodes = []
for i in range(len(freq)):
nodes.append(TreeNode((i, freq[i])))
while len(nodes) > 1:
nodes.sort(key=lambda x: x.val)
left = nodes.pop(0)
right = nodes.pop(0)
new_node = TreeNode((None, left.val + right.val))
new_node.left = left
new_node.right = right
nodes.append(new_node)
# 解码哈夫曼编码
root = nodes
res = []
p = root
for bit in encoded:
if bit == '0':
p = p.left
else:
p = p.right
if not p.left and not p.right:
res.append(p.val)
p = root
return res
freq = [3, 4, 2, 1, 5, 6]
encoded = '011000101101110'
decoded = decode_huffman_tree(encoded, freq)
print(decoded)
```
阅读全文