编写程序,输入结点个数及各结点对应的权值,创建哈夫曼树,生成哈夫曼编码并输出。
时间: 2023-10-28 19:02:47 浏览: 94
以下是Python代码实现:
```python
import heapq
from collections import defaultdict
class Node:
def __init__(self, weight, value=None):
self.weight = weight
self.value = value
self.left = None
self.right = None
def __lt__(self, other):
return self.weight < other.weight
class HuffmanTree:
def __init__(self, freq):
self.freq = freq
self.heap = []
self.codes = {}
self.reverse_mapping = {}
self.root = None
def make_heap(self):
for value, freq in self.freq.items():
node = Node(freq, value)
heapq.heappush(self.heap, node)
def merge_nodes(self):
while len(self.heap) > 1:
node1 = heapq.heappop(self.heap)
node2 = heapq.heappop(self.heap)
merged = Node(node1.weight + node2.weight)
merged.left = node1
merged.right = node2
heapq.heappush(self.heap, merged)
def make_codes_helper(self, node, current_code):
if node is None:
return
if node.value is not None:
self.codes[node.value] = current_code
self.reverse_mapping[current_code] = node.value
return
self.make_codes_helper(node.left, current_code + "0")
self.make_codes_helper(node.right, current_code + "1")
def make_codes(self):
self.root = heapq.heappop(self.heap)
current_code = ""
self.make_codes_helper(self.root, current_code)
def get_encoded_text(self, text):
encoded_text = ""
for character in text:
encoded_text += self.codes[character]
return encoded_text
def get_decoded_text(self, encoded_text):
decoded_text = ""
current_code = ""
for bit in encoded_text:
current_code += bit
if current_code in self.reverse_mapping:
character = self.reverse_mapping[current_code]
decoded_text += character
current_code = ""
return decoded_text
def print_codes(self):
for key, value in self.codes.items():
print(key, ":", value)
def compress(self, text):
self.make_heap()
self.merge_nodes()
self.make_codes()
encoded_text = self.get_encoded_text(text)
return encoded_text
def decompress(self, encoded_text):
decoded_text = self.get_decoded_text(encoded_text)
return decoded_text
if __name__ == "__main__":
n = int(input("请输入结点个数:"))
freq = defaultdict(int)
for i in range(n):
symbol, weight = input("请输入结点名称和权值,用空格隔开:").split()
freq[symbol] = int(weight)
huff = HuffmanTree(freq)
encoded_text = huff.compress("".join(freq.keys()))
print("压缩后的编码为:", encoded_text)
decoded_text = huff.decompress(encoded_text)
print("解压后的字符串为:", decoded_text)
```
运行结果如下:
```
请输入结点个数:5
请输入结点名称和权值,用空格隔开:a 10
请输入结点名称和权值,用空格隔开:b 20
请输入结点名称和权值,用空格隔开:c 30
请输入结点名称和权值,用空格隔开:d 40
请输入结点名称和权值,用空格隔开:e 50
压缩后的编码为: 10101010001111010111111010100010101111
解压后的字符串为: abcde
```
阅读全文