Suppose there's an array with n = 5
int [] arr = {1,2,3,4,5};
and
int [] segmentTree = new int[n*4];
Here's the code for building this segmentTree
buildSegmentTree(a , 1 , 0 , n-1);
void buildSegmentTree(int [] a , int vertex , int leftLimit , int rightLimit)
{
if(leftLimit == rightLimit)
segmentTree[vertex] = a[leftLimit];
else
{
int mid = (leftLimit + rightLimit)/2;
//Builds the left part of the Segment Tree
buildSegmentTree(a , vertex * 2 , leftLimit , mid);
//Builds the right part of the Segment Tree
buildSegmentTree(a , vertex*2 + 1 , mid+1 , rightLimit);
segmentTree[vertex] = segmentTree[vertex*2] + segmentTree[vertex*2 + 1];
}
}
When I print the values of the Segment Tree this is the output that I get
0 15 6 9 3 3 4 5 1 2 0 0 0 0 0 0 0 0 0 0
I understand what these values mean (for example 15 is the sum of 6 and 9), but I dont understand how are they getting stored and how are the calls getting executed.