Input an array, choose sum/min/max/gcd. See the segment tree visualization and get a complete C++ class template to copy.
A segment tree answers a range query in logarithmic time by storing precomputed answers for every power-of-two aligned block. The Segment Tree Builder draws that structure for an array you supply, level by level, and emits a C++ class implementing it for the operation you pick.
Four operations are supported and they share the same shape: sum, min, max and gcd. That is the real lesson of the data structure. Any associative combine function slots into the same recursion, and swapping the operator is all that changes.
The generated template is named after the variable you choose and composes its combine expression from the operand expressions directly rather than by substituting words into a string, so naming your tree l or r does not corrupt the output. It all runs in the page.
1 3 5 7 9 2 4. With sum selected, the root shows 31 and covers the range 0 to 6.1, 3, x, 5 builds over three values.Segment Tree (SUM) — 7 elements
C++ Segment Tree Template
// Segment Tree (SUM) — generated by UtilityToolsLab
// Array: {1, 3, 5, 7, 9, 2, 4} | N = 7
#include <bits/stdc++.h>
using namespace std;
struct SegTree {
int n;
vector<long long> seg;
SegTree(int n) : n(n), seg(4 * n, 0) {}
void build(vector<int>& arr, int node, int l, int r) {
if (l == r) { seg[node] = arr[l]; return; }
int mid = (l + r) / 2;
build(arr, 2*node, l, mid);
build(arr, 2*node+1, mid+1, r);
seg[node] = seg[2*node] + seg[2*node+1];
}
void update(int node, int l, int r, int idx, long long val) {
if (l == r) { seg[node] = val; return; }
int mid = (l + r) / 2;
if (idx <= mid) update(2*node, l, mid, idx, val);
else update(2*node+1, mid+1, r, idx, val);
seg[node] = seg[2*node] + seg[2*node+1];
}
long long query(int node, int l, int r, int ql, int qr) {
if (qr < l || r < ql) return 0LL;
if (ql <= l && r <= qr) return seg[node];
int mid = (l + r) / 2;
auto lv = query(2*node, l, mid, ql, qr);
auto rv = query(2*node+1, mid+1, r, ql, qr);
return lv + rv;
}
// Public wrappers
void update(int idx, long long val) { update(1, 0, n-1, idx, val); }
long long query(int l, int r) { return query(1, 0, n-1, l, r); }
};
int main() {
vector<int> arr = {1, 3, 5, 7, 9, 2, 4};
SegTree st(arr.size());
st.build(arr, 1, 0, arr.size()-1);
// Example: query range [0, 6]
cout << st.query(0, 6) << endl; // sum of entire array
// Example: update index 0 to 100
// st.update(0, 100);
}