1

In segment tree, we build segment tree above an array.
For Example, If array size is 8 [0-7] indexing.
Number of nodes in segment tree is 15 i.e., 1,2,4,8 in 1st,2nd,3rd,4th levls

enter image description here
But in a problem, if I declare structure array size as seg tree[2*N + 1] its giving wrong answer whereas if I declare it as below

struct seg{ 
 int sum;
};
seg tree[4*N + 1];

Its giving wrong answer. My doubt is that [2*N] is sufficient, Then why is it giving wrong answer. enter image description here
Node segment(1-1) having number 9 its parent have number 4. So left child is 2*N right child is 2*N+1

Sparrow
  • 65
  • 2
  • 10

1 Answers1

0

Let n be the size of the initial array. The size of the segment tree will be:

  • 2*n-1 if n is a power of 2.
  • 2*2^(log_2(n)+1)-1 if n is not a power of 2.

Edit: It's true that we can create just an array of size 2*n-1 to make a tree theoretically, but think about the how we can go from parent to children in the array representation of segment tree? The left child will be at index 2*i+1 (0-based indexing) and the right child will be at index 2*i+2. To maintain this invariant, we have to construct the complete binary tree and for that the formula is mentioned above.

You can also refer this.

Community
  • 1
  • 1
Shubham
  • 2,847
  • 4
  • 24
  • 37