【问题标题】:Returning the sum of all nodes in a tree through recursion通过递归返回树中所有节点的总和
【发布时间】:2017-05-03 14:10:43
【问题描述】:

我创建了一个用于 Huffman 编码的算法,它为给定的一组符号及其 pmf 创建 Huffman 树。我的算法使用我自己的 Node 类,它具有实例变量 string symbolfloat probabilitylist childrenstring 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 所在的节点,我怎么能在我的递归函数中实现这一点?我将从每个递归调用返回到哪里?

【问题讨论】:

标签: python recursion huffman-code


【解决方案1】:

没有数据很难进行测试,但这应该会让您更接近目标:

def recursive_len_sum(node):
    temp = 0
    if node.symbol:
        temp += len(node.code)
    for child in node.children:
        temp += recursive_len_sum(child)
    return temp

recursive_len_sum(root)

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 2018-10-31
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2017-07-25
    相关资源
    最近更新 更多