I have to search the sum of numbers between range [3,5] after building a segment tree. For construction of tree I am executing the following code
public static void main(String[] args) {
int arr[] = { 1, 3, 5, 7, 9, 11 };
int n = arr.length;
int tree[] = new int[2 * n];
buildtree(arr, tree, 1, 0, n - 1); // index starts from 1
Arrays.toString(tree).toString();
}
static int buildtree(int arr[], int tree[], int index, int ts, int te) {
if (ts == te) {
tree[index] = arr[ts];
return arr[ts];
}
int mid = (ts + te) / 2;
tree[index] = buildtree(arr, tree, (2 * index), ts, mid) + buildtree(arr, tree, ((2 * index) + 1), mid + 1, te);
return tree[index];
}
I get an exception array index out of bound while storing value for [3,3] . where am i going wrong?