A segment tree is a binary tree where each node represents an interval. Each node stores some property of its corresponding interval: like the maximum/minimum num, the sum of that interval.
Applicable Problems
For any array a
, where every element belongs to some monoid $(S, \oplus)$ we can build a segment tree to answer the following queries (problems):
โ Get(l, r)
โ returns $a_l \oplus a_{l+1} \oplus \dotsb a_r$
โ Change(p, x)
โ set $a_p = x$
- Monoids are semigroups with identity.
- $\oplus$ is an associative binary operation.
- Identity element for some pair $(S, \oplus)$ is such an element $e \in S$ that for every $a \in S$ condition $a โ e = e \oplus a = a$ holds;
Example Problem
Given an integer array
nums
, find the sum of the elements between indices i
and j
(i โค j
), inclusive.The
update(i, val)
function modifies nums by updating the element at index i
to val
.For this problem, the identity element is 0, and the binary operation is + between integers.
And for simplicity we use the identity element to extend the length of the original array to some integer power of 2.
if size of the array is n
, then we only need an array of 2*n
length to store the segment tree. (only in iterative version, property of a Complete Binary Tree)
Define the binary operation
Here we will just use +
for our operation, you can if you need define a merge function for your special operation $\oplus$.
|
|
Build the Tree
We want to construct an array like above (the original array is {1, 2, 3, 4, 5, 6}
), the essential idea of a segment tree is that a node at index $i$ (index starts from 1, you can also try starting from 0, but starting from 1 is simpler) can have two children at indexes $(2 \ast i)$ and $(2 \ast i + 1)$.
|
|
Query a range sum
|
|
Update an element/elements
|
|