I have this algorithm which I modeled off of https://cp-algorithms.com/data_structures/segment_tree.html#structure-of-the-segment-tree.
nums = [1,3,-2,8,-7]
N = len(nums)
tree = [0] * (N* 4)
def build_iterative():
for i in range(N):
tree[i + N] = nums[i]
# then you set the parents
for j in range(N - 1, 0, -1):
tree[j] = tree[j * 2] + tree[j * 2 + 1]
build_iterative()
But it only works for perfect trees aka any array that is a power of 2, but fails for anything that is not perfect. I am not sure why this is the case and cannot figure out what I am missing. Why does this algorithm only work for perfect binary trees? A recursive version will create the correct segment tree array regardless of perfect or full.
Recursive algorithm for comparison which works for any tree perfect or full.
rtree = [0] * (4 * N)
def build_recursively(node, left, right):
if left == right:
rtree[node] = nums[left]
else:
mid = (left + right) // 2
build_recursively(node * 2, left, mid)
build_recursively(node * 2 + 1, mid + 1, right)
rtree[node] = rtree[node * 2] + rtree[node * 2 + 1]
build_recursively(1, 0, N - 1)