0

I have just started learning segment tree. I have tried to build the segment treeusing array. In each parent node, I will store sum of left and right child. Below is my code :

#include <iostream>
using namespace std;
void build(int *A, int *tree, int node, int start, int end)
{
    if(start == end)
    {
        // Leaf node will have a single element
        tree[node] = A[start];
    }
    else
    {
        int mid = (start + end) / 2;
        // Recurse on the left child
        build(A,tree,2*node, start, mid);
        // Recurse on the right child
        build(A,tree,2*node+1, mid+1, end);
        // Internal node will have the sum of both of its children
        tree[node] = tree[2*node] + tree[2*node+1];
    }
}
int main() {
    int a[6]={1,3,5,7,9,11};
    int s[11];
    build(a,s,0,0,5);
    for(int i=0; i<11;i++)
        cout<<s[i]<<" ";
}

So In my segment tree the values should be {36,9,27,4,5,16,11,1,3,7,9} but it is storing {36,27,16,11,7,9,0,0,-1151477072,22004,-1151477840}.

Can anyone help me where I am doing wrong.

Devendra Verma
  • 975
  • 2
  • 10
  • 24

0 Answers0