我在这个主题上看到的几乎每一个在线教程,当涉及到查找子树的大小时,都涉及到在每个子树上调用递归函数。
Python中的问题是,如果递归超过几百个级别,它就会溢出,所以如果理论上我有一个长的线性树,它就会失败。
有没有更好的方法来处理这个问题我需要使用堆栈吗?
最佳答案
我需要使用堆栈吗?
当然,这是一种方法。
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