def merge_nodes(self): # if the tree has more than one node while (len(self.heap) > 1): node_1 = heapq.heappop(self.heap) node_2 = heapq.heappop(self.heap) # merge to one upper node merged = HeapNode(None, node_1.freq + node_2.freq) merged.left = node_1 merged.right = node_2 heapq.heappush(self.heap, merged)
def trees_merge(self): # We pick the 2 trees with the smallest frequency # Combine them into a new tree with a new parent node with the frequency of both of its children # Until you have no more trees to merge while (len(self.heap) > 1): node1 = heapq.heappop( self.heap ) #Pop and return the smallest item from the heap, maintaining the heap invariant node2 = heapq.heappop(self.heap) tree_merged = HeapNode(None, node1.frequency + node2.frequency) tree_merged.left = node1 tree_merged.right = node2 heapq.heappush(self.heap, tree_merged)