Sub topic 6
Building a segment tree and answering range queries
This chapter assumes you know recursion, O(log n) notation, and how a binary tree can be stored in an array with children at 2*node and 2*node+1. It builds a sum segment tree and answers range queries on it. Point updates come in the next chapter.
Build: each node owns a segment
Every node covers a segment [lo, hi] of the array. The root covers [0, n-1]. A node splits at mid = (lo + hi) // 2 into a left child for [lo, mid] and a right child for [mid+1, hi]. A segment of length 1 is a leaf, and it stores the array element. Every other node stores the sum of its two children.
The diagram shows the tree for [5, 2, 7, 1, 3]. Each label gives the array index, the segment, and the stored sum.
The array t is allocated with 4 * n slots. That size is always enough for this layout, even when n is not a power of two, and some slots stay unused. Build visits each node once, so it takes O(n) time.
Query: three cases per node
A query asks for the sum over [l, r], with both bounds inclusive. At each node, compare the query range with the node's segment [lo, hi]:
- No overlap (
r < loorhi < l): return 0, the identity for addition. - Full cover (
l <= loandhi <= r): return the storedt[node]. - Partial overlap: recurse into both children and add the results.
class SegmentTree:
# Sum segment tree over a[0..n-1], inclusive query bounds.
def __init__(self, a):
self.n = len(a)
self.t = [0] * (4 * self.n)
if self.n:
self._build(a, 1, 0, self.n - 1)
def _build(self, a, node, lo, hi):
if lo == hi:
self.t[node] = a[lo]
return
mid = (lo + hi) // 2
self._build(a, 2 * node, lo, mid)
self._build(a, 2 * node + 1, mid + 1, hi)
self.t[node] = self.t[2 * node] + self.t[2 * node + 1]
def query(self, l, r, node=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if r < lo or hi < l:
return 0
if l <= lo and hi <= r:
return self.t[node]
mid = (lo + hi) // 2
return (self.query(l, r, 2 * node, lo, mid)
+ self.query(l, r, 2 * node + 1, mid + 1, hi))
st = SegmentTree([5, 2, 7, 1, 3])
print(st.query(1, 3)) # 2 + 7 + 1 = 10
print(st.query(0, 4)) # 18, answered by the root aloneFor query(1, 3), the root and nodes 2, 4, and 3 partly overlap, so the query recurses into them. Node 8 ([0,0]) and node 7 ([4,4]) lie outside the range and return 0. Nodes 9, 5, and 6 are fully inside and return 2, 7, and 1. The total is 10.
Why this is O(log n)
At each depth, at most two nodes partly overlap the query. These are the nodes that contain a boundary of the range. Every other node visited is a full cover or no overlap, and both return immediately. The tree has about log n levels, so a query visits O(log n) nodes.
Exercise
For the tree above, which stored nodes does query(0, 2) add together, and what is the result?
Show answer
Node 2 covers [0, 2], which is exactly the query range, so it is a full cover and the query returns t[2] = 14 without visiting any deeper node. The root only partly overlaps, so the query recurses into it. Node 3 ([3,4]) lies outside the range and returns 0.