A segment tree is a binary tree that processes range queries over an array or other linear data structure. It follows a divide-and-conquer strategy. It divides an array or range into smaller segments, each carrying a part of the original data, forming a tree-like hierarchy. Each node corresponds to a segment or range of array elements.
Basic Operations of Segment Trees
The following are the basic operations of Segment Trees:
Update
Query
Update
The update operation accepts both the new value to be set and the matching index. After updating the tree array, it must apply comparable modifications to the actual segment tree.
Query
The query() function accepts the query's boundaries, l and r, as inputs and returns the sum of the elements in the array that fall inside these limits.
Working Principle of Segment Trees
Segment trees use divide and conquer.
Divide array segments in half at each level.
Recursively divides until the lower and upper boundaries are equal.
The structure resembles a binary tree.
Complexity Analysis of Operations on Segment Trees