1. 从扩充二叉树到哈弗曼树
扩充二叉树:对二叉树
对于扩充二叉树而言,
- 扩充二叉树新增的结点称为其外部结点(external node);
- 原树
T 的结点称为内部结点(internal node); - 规定空树的扩充二叉树仍为空树;
2. 哈弗曼树的实现
树节点的定义:
class BinTNode:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
哈弗曼树节点的定义:
class HTNode(BinTNode):
def __lt__(self, other):
return self.data < other.data
用小顶堆实现哈弗曼树,极为简洁:
from Queue import PriorityQueue
def HuffmanTree(weights):
trees = PriorityQueue()
map(trees.put, weights)
while trees.qsize() > 1:
trees.put(trees.get() + trees.get())
trees.get()