繁体   English   中英

通过递归返回树中所有节点的总和

[英]Returning the sum of all nodes in a tree through recursion

我已经为霍夫曼编码创建了一个算法,该算法为给定的符号集及其pmf创建霍夫曼树。 我的算法使用我自己的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的节点,我怎么能在递归函数中实现这个?我会从每个递归调用返回哪里?

没有数据就很难测试,但这会让你更接近你的目标:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM