3.4.15 · D3Trees

Worked examples — Segment tree — build, range query, point update

2,393 words11 min readBack to topic

This page is a drill through every situation a sum segment tree can throw at you. We reuse the machinery from the parent note: a Binary Tree over an array, Heap-style indexing (children of node are and , root at index ), and the three query cases (no / total / partial overlap).


The scenario matrix

Cell Scenario class What breaks a beginner
A Build on a power-of-2 array clean tree, warm-up
B Build on a non-power-of-2 array uneven split, why
C Query = whole range root total-overlap, stop instantly
D Query = single index descends to one leaf
E Query entirely inside the left half right subtree never touched
F Query straddling the mid boundary the "at most 4 per level" fact in action
G Point update, then re-query repair the ancestor path only
H Degenerate array root is the leaf
I Word problem (real data) translating English →
J Exam twist: min-tree identity is wrong, is right

The examples below hit every cell. The array we mostly use:


Example 1 — Cell A: build on a power-of-2 array

Figure — Segment tree — build, range query, point update

Example 2 — Cell B: build on a non-power-of-2 array (why )

Figure — Segment tree — build, range query, point update

Example 3 — Cell C: query the whole range


Example 4 — Cell D & E: single-index query inside the left half


Example 5 — Cell F: straddling query (the "4 per level" fact)

Figure — Segment tree — build, range query, point update

Example 6 — Cell G: point update then re-query


Example 7 — Cell H: the degenerate single-element array


Example 8 — Cell I: word problem (real data)


Example 9 — Cell J: the exam twist (min-tree identity)


Recall

Recall Which query cell never touches the right subtree?

A query fully inside the left half ::: Cell E — the right child fails the overlap test in one comparison and returns identity.

Recall Why did

need index ? Non-power-of-2 arrays split unevenly ::: The unbalanced branch pushes a leaf to heap index , which is exactly why we allocate .

Recall After

update(4,100), which nodes changed on ? Only the ancestors of index 4 ::: leaf , then , , and the root — the single root-to-leaf path.

Recall What must a min-tree return on no overlap?

The min identity ::: , never .


Where to go next

  • Handle range updates efficiently → Lazy Propagation.
  • A lighter structure for prefix-style sums only → Fenwick Tree (BIT).
  • The recursion pattern behind build/query → Divide and Conquer.
  • Compare with the naive precompute → Prefix Sum.