I have created an algorithm for Huffman coding that creates the Huffman tree for a given set of symbols, and their pmf. My alogrithm uses my own Node
class which has the instance variables string symbol
, float probability
, list children
, string code
.
I can iterate through my tree recursively as follows:
def print_codes(root):
for child in root.children: # Iterate through children
if (child.symbol): # If node isn't a blank node
print(child.symbol + " = " + child.code) # print its original symbol and code
if (child.children): # If node has children
print_codes(child) # print their codes recursively
Each parent node is a blank node, and each leaf node contains one of the symbols of the albhabet I am encoding. If I wanted to find the total sum of the lengths of each node's code (only the nodes where node.symbol == True
, how could I achieve this in my recursive function? Where would I return from each recursive call?