Exemple #1
0
def construct_tree(freqs):
	# constructs the tree given the frequencies of each character
	nodes = [HuffmanNode(letter, freqs[letter]) for letter in freqs]
	# nodes contains the HuffmanNodes
	trees = [HuffmanTree(node) for node in nodes]
	h = Heap()
	for tree in trees:
		h.insert(tree) # the heap contains all the trees
	while len(h.elems) > 2: # including 0
		t1 = h.minimum() # extract the two least frequent letters
		h.delete()
		t2 = h.minimum()
		h.delete()
		newTree = combine(t2, t1) # create a new tree combining the two nodes
		h.insert(newTree) # insert the new tree back into the heap
	# at this point, the heap contains only one element
	return h.minimum()