Segment Tree Build?

218 Views Asked by At

I am getting conflicting evidence on the build time complexity for a recursive segment tree.

Some sources(wikipedia) claim it's O(N*log(N)), while others claim it's O(N). My intuition says it's O(N), because we have 2N nodes and 2N-1 edges.

Which one is it?

Note: We're building the segment tree with a function like such:

private int build(int[] a, int i, int l, int r){
    if(l == r){
      nodes[i] = a[l];
    }else{
      nodes[i] = Math.min(build(a, i*2, l, (l+r)/2),
      build(a, i*2+1, (l+r)/2+1, r));
    }
    return nodes[i];
  }

we're not doing point update for each value in the array.

2

There are 2 best solutions below

0
On

Assuming the original array a with size N, since each node of the tree gets divided into two, the total quantity of elements of the tree is next to N*log(N). This way, the build have complexity of O(N*log(N)) and each query O(log(N)).

This value 2N is just an estimated upper bound for the number of nodes, which actually also works, but it is actually closer to N*log(N) than to 2N.

0
On

Notice that its just a DFS algorithm and DFS time complexity is O(|V| + |E|).

So it means the complexity is O(2n + 2n - 1) = O(n)