【发布时间】:2017-05-03 14:10:43
【问题描述】:
我创建了一个用于 Huffman 编码的算法,它为给定的一组符号及其 pmf 创建 Huffman 树。我的算法使用我自己的 Node 类,它具有实例变量 string symbol、float probability、list children、string code。
我可以递归地遍历我的树,如下所示:
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
每个父节点都是一个空白节点,每个叶节点都包含我正在编码的 albhabet 的符号之一。如果我想找到每个节点代码长度的总和(只有 node.symbol == True 所在的节点,我怎么能在我的递归函数中实现这一点?我将从每个递归调用返回到哪里?
【问题讨论】:
-
尝试应用 stackoverflow.com/a/42147213/674064 的方法。而不是“输入更小的 1 个元素”假设树的深度更小一层。
标签: python recursion huffman-code