Sub topic 7
Point updates in a segment tree
This chapter assumes you know how the segment tree is built and queried: node 1 is the root, the children of node are 2*node and 2*node+1, and each node stores the combined value of its segment. Here we change one element and repair the tree in O(log n).
What changes when one element changes
Setting a[i] to a new value affects only the segments that contain position i. Every other node stores a result that does not depend on a[i]. Those containing segments form one root-to-leaf path, one node per level, and a tree over n elements has about log₂ n + 1 levels.
The update therefore has two steps:
- Walk down to the leaf for
i, choosing the left or right child by comparingiwithmid. - Write the new value into the leaf. On the way back up, recompute each node on the path from its two children.
The updated path is nodes 1, 2 and 5. Nodes 3 and 4 keep their old values.
The code
This listing includes the build and query methods from the previous chapter, so it runs as shown.
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 update(self, i, value, node=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if lo == hi:
self.t[node] = value
return
mid = (lo + hi) // 2
if i <= mid:
self.update(i, value, 2 * node, lo, mid)
else:
self.update(i, value, 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
st.update(2, 10)
print(st.query(1, 3)) # 2 + 10 + 1 = 13
print(st.query(0, 4)) # 21Unlike query, update makes only one recursive call per level, so it does O(log n) work. A query can visit two branches at a level, but it still touches O(log n) nodes in total.
Design points
- The update assigns a value. It does not add a delta. To add
dtoa[i], read the current value first, or change the leaf line toself.t[node] += d. - Parents are recomputed from their children. The code does not patch a parent with the change in the leaf. Recomputing works for any associative operation, including
min,maxandgcd, which have no inverse. Patching works only for sums. - Recursion depth is small. The depth is about log₂ n, so Python's recursion limit is not a concern for realistic n.
- Bounds are not checked. An
ioutside0..n-1ends up in a leaf for some other index, or in an unused slot. Validateiat the call site.
Exercise
For the tree built from [5, 2, 7, 1, 3], which node numbers does st.update(0, 1) rewrite, and how many are there?
Show answer
Nodes 1, 2, 4 and 8, which is four nodes. The path goes from the root [0,4] to [0,2], then [0,1], then the leaf [0,0] at node 8. That is the full height of the tree for n = 5.