Data Structures · Visualization
Segment Tree: Build
Segment Tree
Building a segment tree fills in every node's value, starting from the leaves (which just copy the original array's values) and working upward, combining each pair of children into their parent. Time: O(n) total (each node built once). Space: O(n) for the tree.
Big-O: Build O(n); range query and point update O(log n).
Segment Tree: Build
Segment TreeBuilding a segment tree fills in every node's value, starting from the leaves (which just copy the original array's values) and working upward, combining each pair of children into their parent. This is naturally done with a recursive function that splits the range in half at every step.
How Build Works
- If the current range covers a single element, make it a leaf storing that element's value.
- Otherwise, split the range into two halves.
- Recursively build the left half and the right half.
- Combine the two halves' values (e.g. add them for a sum tree) to get the current node's value.
Build Worked Example
Input: Build a sum segment tree over [2, 4, 6]
- Range [2,4,6] splits into [2,4] and [6]
- [2,4] splits into [2] and [4], combine → 6
- [6] is a single-element leaf → 6
- Combine [2,4]=6 and [6]=6 → root = 12
Output: Root value: 12 (matches sum of [2,4,6])
Press ▶ Run to watch it step by step.
def build(base):
n = len(base)
tree = [2, 4, 6]
for i in range(n):
tree[n + i] = base[i] # leaves
for i in range(n - 1, 0, -1):
tree[i] = tree[2*i] + tree[2*i+1]
return tree
# O(n)
# example: build on [2, 4, 6]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Build Time & Space Complexity
When to Use Build
- The required setup step before any range queries or updates can run
- Preprocessing static data for fast repeated range queries
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.