def __init__(self, words_stats): heap = Heap(True) for word in words_stats: node = TreeNode(word) node.setValue(words_stats[word]) heap.insert(node) self.root = HuffmanBinaryTree.buildTree(words_stats, heap)
def buildTree(words_stats, heap): if heap.size() == 1: root = TreeNode("Internal") root.setLeftEdgeVal(1) node = heap.extract() root.setLeft(node) return root elif heap.size() == 2: root = TreeNode("Internal") root.setLeftEdgeVal(1) root.setRightEdgeVal(0) node1 = heap.extract() root.setLeft(node1) node2 = heap.extract() root.setRight(node2) return root else: copy_stats = words_stats.copy() node1 = heap.extract() node2 = heap.extract() new_node = TreeNode(node1.getName() + "/" + node2.getName()) new_node.setValue(node1.getValue() + node2.getValue()) del copy_stats[node1.getName()] del copy_stats[node2.getName()] copy_stats[node1.getName() + "/" + node2.getName()] = node1.getValue() + node2.getValue() heap.insert(new_node) root = HuffmanBinaryTree.buildTree(copy_stats, heap) new_node.setName("Internal") new_node.setValue(0.0) new_node.setLeftEdgeVal(1) new_node.setRightEdgeVal(0) new_node.setLeft(node1) new_node.setRight(node2) return root