07_06.哈夫曼树
实数集w={2, 3, 7, 10, 4, 2, 5},构造一棵哈夫曼树
在(2)中,存在两个权值为4的树,可以选择其中任意一个与权值为3的树合并。不同选择会导致不同的哈夫曼树,但其外部路径的长度一定相等。
from trees.prioqueue import PrioQueue # 优先队列 (较小数优先) from trees.linktree import levelorder # 引入宽度优先遍历 class BinTNode: """二叉树结点""" def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right class HTNode(BinTNode): """哈夫曼树节点类""" def __le__(self, othernode): return self.data <= othernode.data class HuffmanPrioQ(PrioQueue): """哈夫曼优先队列""" def number(self): return len(self._elems) def HuffmanTree(weights): trees = HuffmanPrioQ() for w in weights: trees.enqueue(HTNode(w)) while trees.number() > 1: t1 = trees.dequeue() t2 = trees.dequeue() x = t1.data + t2.data trees.enqueue(HTNode(x, t1, t2)) return trees.dequeue() wlist = [2, 3, 7, 10, 4, 2, 5] h = HuffmanTree(wlist) print(levelorder(h)) # 33 14 19 7 7 9 10 3 4 4 5 2 2 None