I'm trying to understand the process of building a segment tree using Python. I've come up with a function like this (which works):
arr = [ ... ]
tree = [None] * (4*len(arr))
def build(v, vl, vr):
if vl == vr:
tree[v] = arr[vl]
return
vm = (vl + vr) // 2
build(2*v + 1, vl, vm)
build(2*v + 2, vm + 1, vr)
tree[v] = tree[2*v + 1] + tree[2*v + 2]
build(0, 0, len(arr) - 1)
How can I make this build function iterative (w/o recursion)? Also, what's the time complexity of building a segment tree this way? Some tutorials state that it's O(n)
, but don't the recursive calls make it O(n*log(n))
?