MCPcopy
hub / github.com/TheAlgorithms/Python / build_tree

Function build_tree

data_compression/huffman.py:38–51  ·  view source on GitHub ↗

Run through the list of Letters and build the min heap for the Huffman Tree.

(letters: list[Letter])

Source from the content-addressed store, hash-verified

36
37
38def build_tree(letters: list[Letter]) -> Letter | TreeNode:
39 """
40 Run through the list of Letters and build the min heap
41 for the Huffman Tree.
42 """
43 response: list[Letter | TreeNode] = list(letters)
44 while len(response) > 1:
45 left = response.pop(0)
46 right = response.pop(0)
47 total_freq = left.freq + right.freq
48 node = TreeNode(total_freq, left, right)
49 response.append(node)
50 response.sort(key=lambda x: x.freq)
51 return response[0]
52
53
54def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:

Callers 1

huffmanFunction · 0.70

Calls 4

sortMethod · 0.80
TreeNodeClass · 0.70
popMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected