子树在Python尺寸 [英] Size of subtree in Python

查看:249
本文介绍了子树在Python尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎所有的在线教程中,我对这个问题看,当涉及到找到一个子树的大小,包括呼吁每个孩子的子树递归函数。

与此Python中的问题是,它溢出如果递归过去几百的水平,所以如果我理论上有很长的,线性树,它会失败。

有没有更好的方式来处理呢?我是否需要使用堆栈呢?

解决方案
  

我是否需要使用堆栈呢?

当然,这是做的一种方式。

 高清iter_tree(根):
    to_explore = [根]
    而to_explore:
        节点= to_explore.pop()
        产量节点
        对于孩子在node.children:
            to_explore.append(子)

高清尺寸(根):
    数= 0
    在iter_tree(根)节点:
        数+ = 1
    返回计数
 

Almost every online tutorial I see on the subject when it comes to finding the size of a subtree involves calling a recursive function on each child's subtree.

The problem with this in Python is that it overflows if you recurse past a few hundred levels, so if I theoretically had a long, linear tree, it would fail.

Is there a better way to handle this? Do I need to use a stack instead?

解决方案

Do I need to use a stack instead?

Sure, that's one way of doing it.

def iter_tree(root):
    to_explore = [root]
    while to_explore:
        node = to_explore.pop()
        yield node
        for child in node.children:
            to_explore.append(child)

def size(root):
    count = 0
    for node in iter_tree(root):
        count += 1
    return count

这篇关于子树在Python尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆