哈夫曼算法实现(python语言)

# -*- coding: UTF-8 -*-


class HTNode(BinTNode):
    def __lt__(self, othernode):
        return self.data < othernode.data


class HuffmanPrioQueue(PrioQueue):
    def number(self):
        return len(self._elems)


def huffman_tree(weights):
    trees = HuffmanPrioQueue()
    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()

你可能感兴趣的:(python数据结构与算法)