数据结构2. 请编程实现哈夫曼树的构造,以及对该赫夫曼树的编码。
时间: 2024-05-01 16:20:57 浏览: 115
以下是Python代码实现哈夫曼树的构造和编码:
```python
class Node:
def __init__(self, value, freq):
self.value = value
self.freq = freq
self.left = None
self.right = None
def freq_dict(s):
freq = {}
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
return freq
def huffman_tree(s):
freq = freq_dict(s)
nodes = [Node(k, v) for k, v in freq.items()]
while len(nodes) > 1:
nodes = sorted(nodes, key=lambda x: x.freq)
left = nodes.pop(0)
right = nodes.pop(0)
parent = Node(left.value + right.value, left.freq + right.freq)
parent.left = left
parent.right = right
nodes.append(parent)
return nodes[0]
def huffman_encoding(s, root, code=''):
if root.left is None and root.right is None:
return {root.value: code}
codes = {}
codes.update(huffman_encoding(s, root.left, code + '0'))
codes.update(huffman_encoding(s, root.right, code + '1'))
return codes
s = 'hello world'
root = huffman_tree(s)
codes = huffman_encoding(s, root)
print(codes)
```
其中,我们定义了一个`Node`类来表示哈夫曼树的节点,包括节点的值(即字符)和频率,以及左右子节点。然后我们实现了`freq_dict`函数来统计字符串中每个字符出现的频率。接着,我们实现了`huffman_tree`函数来构造哈夫曼树。最后,我们实现了`huffman_encoding`函数来对哈夫曼树进行编码,返回每个字符对应的编码。
阅读全文