Sub topic 5
Segment tree: splitting an array into segments
This chapter assumes you know zero-based indexing, O(log n), and basic recursion and binary trees. It covers what a segment tree stores and how it is laid out. Build, query, and update come in the next chapters.
The idea
A segment tree divides an array into segments and stores one summary value per segment. For a sum tree, each node holds the sum of its segment.
- The root covers the whole array,
[0, n-1]. - Every node with more than one element splits its segment at
mid = (lo + hi) // 2. The left child gets[lo, mid]and the right child gets[mid+1, hi]. - A node with
lo == hiis a leaf. It holds one array element.
Each parent's value combines its two children's values. That one rule is what makes updates and queries fast later. A change to one element affects only the nodes on one root-to-leaf path. A query can often use a single stored node in place of a whole run of elements.
An example
For a = [5, 2, 7, 1, 3], the tree looks like this:
The array has five elements, which is not a power of two. The tree is still valid, but it is not perfectly balanced. Segment sizes differ by at most one at each split, so the leaves sit at depth 2 or 3.
Numbering the nodes
The tree is stored in a flat array. The root is node 1. Node k has children 2*k and 2*k+1. This code prints the segment that each node index covers:
def layout(node, lo, hi, depth=0):
print(" " * depth + f"node {node}: [{lo}, {hi}]")
if lo == hi:
return
mid = (lo + hi) // 2
layout(2 * node, lo, mid, depth + 1)
layout(2 * node + 1, mid + 1, hi, depth + 1)
layout(1, 0, 4)It prints:
node 1: [0, 4]
node 2: [0, 2]
node 4: [0, 1]
node 8: [0, 0]
node 9: [1, 1]
node 5: [2, 2]
node 3: [3, 4]
node 6: [3, 3]
node 7: [4, 4]Node indices skip values (there is no node 10 or higher here), because shallow leaves leave gaps in the numbering.
Why the array has size 4n
The tree's height is ceil(log2 n), so there are ceil(log2 n) + 1 levels, numbered from depth 0. In the worst case the deepest nodes get indices close to 2^(ceil(log2 n) + 1). That value is less than 4n. Allocating 4 * n slots is a safe bound that does not depend on n being a power of two. Some slots stay unused.
Why the depth matters
Every operation walks from the root toward the leaves, so its cost follows the height, which is O(log n). A range query visits at most about four nodes per level. That keeps it at O(log n), where a plain loop over the range costs O(n).
Exercise
For n = 6, list the segments of the root's two children and of the left child's two children.
Show answer
The root is [0, 5], with mid = 2. Its children are [0, 2] (node 2) and [3, 5] (node 3). Node 2 has mid = 1 and splits into [0, 1] (node 4) and [2, 2] (node 5). Node 3 has mid = 4 and splits into [3, 4] (node 6) and [5, 5] (node 7).