UtilityToolsLab

© 2026 UtilityToolsLab. Built and maintained by the UtilityToolsLab Team.

Free eBooks·About·Changelog·Privacy Policy·Terms of Service·Report a bug
HomeCompetitive ProgrammingSegment Tree

Related Tools

Code FormatterMatrix GeneratorComplexity CalcBit VisualizerBitmask PlannerPrime FactorsMEX CalcInterval MergerMatrix RotationPBDS GeneratorGraph VisualizerStress TesterModulo CalcConvex HullPath FinderOffline JudgeBig-O AnalyzerCombinatoricsDP Table BuilderExtended GCDSieve VisualizerBinary SearchSorting VisualizerSparse Table RMQUnion-Find DSU

Segment Tree Blueprint

Input an array, choose sum/min/max/gcd. See the segment tree visualization and get a complete C++ class template to copy.

You Might Also Like

All Competitive Programming

Interval Merger

Input pairs of ranges like [1,4],[3,7]. Visualizes overlaps on a timeline and collapses them into merged segments instantly.

Code Formatter

Format and beautify C++, Java, and Python code with consistent indentation. 100% client-side — no code leaves your browser.

PBDS Generator

Generate ready-to-paste C++ Order Statistics Tree code. Configure key type, comparator, and duplicate support. One-click copy.

Stress Tester

Paste your brute force, optimal solution and test generator to get a downloadable Python or Bash stress-test script that finds counter-examples.

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.

Walkthrough: Building Over Seven Values

  1. The array loads as 1 3 5 7 9 2 4. With sum selected, the root shows 31 and covers the range 0 to 6.
  2. Read down a level. The root splits at the midpoint into a left child covering 0 to 3 and a right child covering 4 to 6, and their values sum to the root.
  3. Switch the operation to min. The tree shape is identical and only the values change, with the root now reading 1. Switch to max and it reads 9.
  4. Rename the tree in the name field and watch the C++ template update, including the usage example at the bottom which queries the full range.
  5. Press the copy button for the whole class. It arrives with build, query and update already written against your chosen operation.

How Big the Visual Tree Gets

  • The array is capped at 16 elements. Anything beyond that is dropped from the visualisation, though the generated C++ has no such limit.
  • Only 5 levels are rendered. A 16-element array needs exactly 5, which is why that pair of numbers was chosen together.
  • Internal storage is allocated at 4 times the array length, the standard safe bound for a recursively indexed segment tree with children at 2i and 2i+1.
  • An empty or unparseable array draws nothing rather than an error, and non-numeric tokens are filtered out silently, so 1, 3, x, 5 builds over three values.
  • The gcd combine treats a zero as the identity, which is correct: the gcd of 0 and n is n, and that is what makes the operation associative over the whole array.

Segment Tree (SUM) — 7 elements

[0,6]31
[0,3]16
[4,6]15
[0,1]4
[2,3]12
[4,5]11
[6,6]4
[0,0]1
[1,1]3
[2,2]5
[3,3]7
[4,4]9
[5,5]2

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);
}