求哈夫曼编码的递归算法
时间: 2023-12-22 15:28:42 浏览: 75
以下是哈夫曼编码的递归算法演示:
```python
class Node:
def __init__(self, symbol, freq):
self.symbol = symbol
self.freq = freq
self.left = None
self.right = None
def huffman_coding(data):
def build_huffman_tree(freq_dict):
nodes = [Node(symbol, freq) for symbol, freq in freq_dict.items()]
while len(nodes) > 1:
nodes = sorted(nodes, key=lambda x: x.freq)
left = nodes.pop(0)
right = nodes.pop(0)
parent = Node(None, left.freq + right.freq)
parent.left = left
parent.right = right
nodes.append(parent)
return nodes[0]
def generate_huffman_code(node, current_code, huffman_codes):
if node.symbol is not None:
huffman_codes[node.symbol] = current_code
else:
generate_huffman_code(node.left, current_code + "0", huffman_codes)
generate_huffman_code(node.right, current_code + "1", huffman_codes)
freq_dict = {}
for symbol in data:
if symbol in freq_dict:
freq_dict[symbol] += 1
else:
freq_dict[symbol] = 1
root = build_huffman_tree(freq_dict)
huffman_codes = {}
generate_huffman_code(root, "", huffman_codes)
return huffman_codes
data = "Huffman coding is a data compression algorithm."
huffman_table = huffman_coding(data)
print(huffman_table)
```
阅读全文