# 数据结构-哈夫曼树（python实现）

## 哈夫曼树（Huffman Tree）

sourceData = [('a', 8), ('b', 5), ('c', 3), ('d', 3), ('e', 8), ('f', 6), ('g', 2), ('h', 5), ('i', 9), ('j', 5), ('k', 7), ('l', 5), ('m', 10), ('n', 9)]


1. 首先，找出所有元素中权重最小的两个元素，即g(2)和c(3)，
2. 以g和c为子节点构建二叉树，则构建的二叉树的父节点的权重为 2+3 = 5.
3. 从除g和c以外剩下的元素和新构建的权重为5的节点中选出权重最小的两个节点，
4. 进行第 2 步操作。

class BinaryTree:
def __init__(self, data, weight):
self.data = data
self.weight = weight
self.left = None
self.right = None


# 定义获取列表中权重最大的两个节点的方法：
def min2(li):
result = [BinaryTree(None, float('inf')), BinaryTree(None, float('inf'))]
li2 = []
for i in range(len(li)):
if li[i].weight < result[0].weight:
if result[1].weight != float('inf'):
li2.append(result[1])
result[0], result[1] = li[i], result[0]
elif li[i].weight < result[1].weight:
if result[1].weight != float('inf'):
li2.append(result[1])
result[1] = li[i]
else:
li2.append(li[i])
return result, li2


def makeHuffman(source):
m2, data = min2(source)
print(m2[0].data, m2[1].data)
left = m2[0]
right = m2[1]

sumLR = left.weight + right.weight
father = BinaryTree(None, sumLR)
father.left = left
father.right = right
if data == []:
return father
data.append(father)
return makeHuffman(data)


# 递归方式实现广度优先遍历

if type(gen) == BinaryTree:
gen = [gen]
result.append((gen[index].data, gen[index].weight))
if gen[index].left != None:
nextGen.append(gen[index].left)
if gen[index].right != None:
nextGen.append(gen[index].right)

if index == len(gen)-1:
if nextGen == []:
return
else:
gen = nextGen
nextGen = []
index = 0
else:
index += 1

return result


# 某篇文章中部分字母根据出现的概率规定权重
sourceData = [('a', 8), ('b', 5), ('c', 3), ('d', 3), ('e', 8), ('f', 6), ('g', 2), ('h', 5), ('i', 9), ('j', 5), ('k', 7), ('l', 5), ('m', 10), ('n', 9)]
sourceData = [BinaryTree(x[0], x[1]) for x in sourceData]


huffman = makeHuffman(sourceData)


OK ，我们的哈夫曼树就介绍到这里了，你还有什么不懂的问题记得留言给我哦。

posted @ 2019-07-22 22:30  目标进大厂的柳乘风  阅读(1386)  评论(2编辑  收藏