Python树遍历递归深度超出

时间:2011-10-09 17:22:00

标签: python algorithm optimization tree

我有一个段树,它包含一系列数字的数据(选择的数据结构here)。这是代码:

class SegmentTree:
    def __init__(self, N):
        def _init(b, e):
            if b is e:
                data = foo() # No dependency
                return Node(b, e, data, None, None)
            else:
                mid = (b + e ) / 2

                L = _init(b, mid)
                R = _init(mid + 1, e)

                data = foo() #Data depends on L and R

                return Node(b, e, data, L, R)

        self.root = _init(1, N)

对于大约300的N,超出最大递归深度错误时失败。有没有办法迭代地创建树而不是递归?

2 个答案:

答案 0 :(得分:6)

真正的问题不是你的算法的递归深度,对于像300这样的值应该是大约10,但是你要将数字与is进行比较。 is关键字检查对象标识,而==检查是否相等:

>>> 300 == 299+1
True
>>> 300 is 299+1
False

因为即使ifb相等,你的e条件终止递归也永远不会成立,函数会不断递归。

如果您更改if此问题应该消失:

if b == e:
   ...

对于较小的数字,问题可能不会发生,因为Python "caches" and reuses the objects的内容达到一定的大小。

答案 1 :(得分:1)

通常,从递归转换为迭代的方式是手动维护堆栈(或队列)。

类似的东西:

 while stack is not empty:
     item = pop from stack

     do processing (such as adding onto the node)

     push L and R onto the stack

堆栈确实会在内存中增长,因为对于你弹出的每个项目,你都在推动两个。