数据结构-哈夫曼树(python实现) (2)

获取节点列表中权重最小的两个节点:

# 定义获取列表中权重最大的两个节点的方法: 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)

定义广度优先遍历方法:

# 递归方式实现广度优先遍历 def breadthFirst(gen, index=0, nextGen=[], result=[]): 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 breadthFirst(gen, index, nextGen,result) 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) print(breadthFirst(huffman))

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppfsw.html