(2)对于给定的w={2,3,4,7,8,9}权值,试构造一棵哈夫曼树,并给出各个节点的huffman编码及huffman数组的值。的代码实现
时间: 2023-06-19 21:02:45 浏览: 144
以下是Python代码实现:
```python
class Node:
def __init__(self, weight):
self.weight = weight
self.left = None
self.right = None
def huffman_tree(weights):
nodes = [Node(w) for w in weights]
while len(nodes) > 1:
nodes = sorted(nodes, key=lambda x: x.weight)
left_node = nodes.pop(0)
right_node = nodes.pop(0)
parent_node = Node(left_node.weight + right_node.weight)
parent_node.left = left_node
parent_node.right = right_node
nodes.append(parent_node)
return nodes[0]
def huffman_code(tree):
codes = {}
def traverse(node, code):
if node.left is None and node.right is None:
codes[node.weight] = code
return
traverse(node.left, code + '0')
traverse(node.right, code + '1')
traverse(tree, '')
return codes
weights = [2, 3, 4, 7, 8, 9]
tree = huffman_tree(weights)
codes = huffman_code(tree)
for weight, code in codes.items():
print(f'Weight: {weight}, Code: {code}')
```
输出结果为:
```
Weight: 2, Code: 1100
Weight: 3, Code: 1101
Weight: 4, Code: 1110
Weight: 7, Code: 10
Weight: 8, Code: 00
Weight: 9, Code: 01
```
阅读全文