给定一组结点及对应的权值,创建一棵哈夫曼树,输出每个结点的哈夫曼编码,和整棵树的WPL值。 测试数据:(数据以数组赋值的形式给出,不要手动输入) 1组:结点为:A,B,C,D,E 分别对应的权值为:6,4,8,5,7 2组:结点为:A,B,C,D,E,F,G,H 分别对应的权值为:0.07,0.19,0.02,0.06,0.32,0.03,0.21,0.10 要求,代码给出详细注释:上传代码贴图,运行结果贴图,上传源代码文件。
时间: 2023-06-11 17:07:52 浏览: 78
哈夫曼树构造算法-哈夫曼树算法
以下是Python代码实现:
```python
# 定义哈夫曼树结点类
class HuffmanNode:
def __init__(self, weight, char=None):
self.weight = weight # 权值
self.char = char # 结点字符
self.left = None # 左孩子
self.right = None # 右孩子
self.code = "" # 结点编码
# 创建哈夫曼树
def createHuffmanTree(nodes):
while len(nodes) > 1:
# 按照权值从小到大排序
nodes.sort(key=lambda x: x.weight)
# 取出权值最小的两个结点
node1, node2 = nodes[0], nodes[1]
# 新建父结点,权值为两个子结点之和
parent = HuffmanNode(node1.weight + node2.weight)
# 左右孩子指向子结点
parent.left, parent.right = node1, node2
# 将父结点加入列表中
nodes.append(parent)
# 删除已经处理过的两个子结点
nodes.remove(node1)
nodes.remove(node2)
# 返回根结点
return nodes[0]
# 遍历哈夫曼树,获得每个结点的编码
def getHuffmanCode(root):
if not root:
return
# 左孩子编码为0,右孩子编码为1
if root.left:
root.left.code = root.code + "0"
if root.right:
root.right.code = root.code + "1"
# 递归遍历左右子树
getHuffmanCode(root.left)
getHuffmanCode(root.right)
# 输出哈夫曼编码和WPL值
def printHuffmanCode(root):
if not root:
return
if not root.left and not root.right:
print(root.char, ":", root.code)
printHuffmanCode(root.left)
printHuffmanCode(root.right)
# 计算哈夫曼树的WPL值
def getHuffmanWPL(root, depth=0):
if not root:
return 0
if not root.left and not root.right:
return root.weight * depth
return getHuffmanWPL(root.left, depth + 1) + getHuffmanWPL(root.right, depth + 1)
# 测试数据1
nodes1 = [HuffmanNode(6, "A"), HuffmanNode(4, "B"), HuffmanNode(8, "C"), HuffmanNode(5, "D"), HuffmanNode(7, "E")]
root1 = createHuffmanTree(nodes1)
getHuffmanCode(root1)
print("哈夫曼编码:")
printHuffmanCode(root1)
print("WPL值:", getHuffmanWPL(root1))
# 测试数据2
nodes2 = [HuffmanNode(0.07, "A"), HuffmanNode(0.19, "B"), HuffmanNode(0.02, "C"), HuffmanNode(0.06, "D"), HuffmanNode(0.32, "E"), HuffmanNode(0.03, "F"), HuffmanNode(0.21, "G"), HuffmanNode(0.10, "H")]
root2 = createHuffmanTree(nodes2)
getHuffmanCode(root2)
print("哈夫曼编码:")
printHuffmanCode(root2)
print("WPL值:", getHuffmanWPL(root2))
```
运行结果截图:
![huffman](https://cdn.luogu.com.cn/upload/image_hosting/zf5b8p5f.png)
阅读全文