请给出建立一个哈夫曼树的完整代码
时间: 2023-09-18 20:07:13 浏览: 95
赫夫曼树建立的代码
以下是建立哈夫曼树的完整代码,包括构建哈夫曼树、编码和解码:
```python
import heapq
from collections import defaultdict
class HuffmanCoding:
def __init__(self, text):
self.text = text
self.freq = defaultdict(int)
self.heap = []
self.codes = {}
self.reverse_mapping = {}
# 构建哈夫曼树
def make_heap(self):
for char in self.text:
self.freq[char] += 1
for char in self.freq:
heapq.heappush(self.heap, (self.freq[char], char))
def merge_codes(self):
while len(self.heap) > 1:
freq1, char1 = heapq.heappop(self.heap)
freq2, char2 = heapq.heappop(self.heap)
merged_freq = freq1 + freq2
merged_char = char1 + char2
heapq.heappush(self.heap, (merged_freq, merged_char))
def make_codes_helper(self, root, current_code):
if root is None:
return
if len(root) == 1:
char = root
self.codes[char] = current_code
self.reverse_mapping[current_code] = char
return
left, right = root
self.make_codes_helper(left, current_code + "0")
self.make_codes_helper(right, current_code + "1")
def make_codes(self):
root = heapq.heappop(self.heap)
self.make_codes_helper(root, "")
# 编码
def get_encoded_text(self):
encoded_text = ""
for char in self.text:
encoded_text += self.codes[char]
return encoded_text
# 解码
def get_decoded_text(self, encoded_text):
current_code = ""
decoded_text = ""
for bit in encoded_text:
current_code += bit
if current_code in self.reverse_mapping:
char = self.reverse_mapping[current_code]
decoded_text += char
current_code = ""
return decoded_text
# 压缩
def compress(self):
self.make_heap()
self.merge_codes()
self.make_codes()
encoded_text = self.get_encoded_text()
return encoded_text
# 解压缩
def decompress(self, encoded_text):
decoded_text = self.get_decoded_text(encoded_text)
return decoded_text
```
使用示例:
```python
text = "hello world"
h = HuffmanCoding(text)
encoded_text = h.compress()
decoded_text = h.decompress(encoded_text)
print(f"原文: {text}")
print(f"压缩后: {encoded_text}")
print(f"解压缩后: {decoded_text}")
```
阅读全文