数据结构(Python) 由若干个值无重复的叶子结点及其权值,建立相应的哈夫曼树。要求哈夫曼树中所有左孩子权值小于等于右孩子权值。对所建的哈夫曼树,根据左0右1的原则,对各叶子结点进行编码。对给定的二进制码串进行相应的解码,并输出解码字符串。 输入格式: 有多组测试数据,每组数据由结点信息和码串两部分组成。结点信息最后一行为# #,每个结点信息包括一个字符和一个整数,表示结点字符值和权值;码串部分的为一行,由0和1构成的二进制码串且均有效。 输出格式: 在一行里输出二进制码串对应的解码字符串。 输入样例: 在这里给出一组输入。例如: O 2 D 4 G 5 A 7 # # 1011011011111111010 输出样例: 在这里给出相应的输出。例如: GOODDOG
时间: 2024-02-17 07:04:22 浏览: 63
以下是 Python 代码实现,可以通过本地 IDE 进行调试。
```python
import heapq
class Node:
def __init__(self, char, freq):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
return self.freq < other.freq
def encode(root, code, codes):
if root.left is None and root.right is None:
codes[root.char] = code
return
encode(root.left, code + "0", codes)
encode(root.right, code + "1", codes)
def huffman_encoding(s):
freq = {}
for char in s:
if char not in freq:
freq[char] = 0
freq[char] += 1
heap = []
for char, freq in freq.items():
heapq.heappush(heap, Node(char, freq))
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
parent = Node(None, node1.freq + node2.freq)
parent.left = node1
parent.right = node2
heapq.heappush(heap, parent)
root = heap[0]
codes = {}
encode(root, "", codes)
encoded = ""
for char in s:
encoded += codes[char]
return root, encoded
def huffman_decoding(root, s):
decoded = ""
node = root
for char in s:
if char == "0":
node = node.left
else:
node = node.right
if node.left is None and node.right is None:
decoded += node.char
node = root
return decoded
while True:
nodes = []
while True:
node_info = input().split()
if node_info[0] == "#" and node_info[1] == "#":
break
nodes.append(Node(node_info[0], int(node_info[1])))
s = input().strip()
root, encoded = huffman_encoding(s)
decoded = huffman_decoding(root, encoded)
print(decoded)
```
阅读全文