我刚刚开始学习segment tree
。我试图建立segment tree
using数组。在每个父节点中,我将存储左右子节点的和。下面是我的代码:
#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]<<" ";
}
因此,在我的细分树中,值应为{36,9,27,4,5,16,11,1,3,7,9}
,但它存储的是{36,27,16,11,7,9,0,0,-1151477072,22004,-1151477840}。
任何人都可以在我做错地方帮助我。