Segment Trees
Segment trees are a unique application of trees that help to solve problems that involve many range queries over an array
The fundamental idea of segment trees is that each leaf corresponds to an element in the array (by index) and each subsequent parent represents a range of that array, i..j. As a result, while segment trees can be represented as an actual tree, it can also just be represented directly using an array.
Implementation
Building
Build from bottom up using merge sort like algorithms
void build(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(2*node, start, mid);
// Recurse on the right child
build(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];
}
}Updating
Querying
When querying for a range, we're simply looking for the ranges (represented by our nodes) that fully encompass our search range
Last updated