Segment Tree - Sum of given Range
Let us consider the following problem to understand Segment Trees.
We have an array arr[0... n-1]. We should be able to
Range sum with nested loops:
Running a loop from l to r and computing the sum of the elements in the provided range is a straightforward solution. Just enter arr[i] = x to change a value. While the first operation requires O(n) time, the second only needs O(1) time.
Range total using Prefix Sum:
An alternative is to make a new array and place the total from start to I at the ith index. The update procedure now requires O(n) time, while the total of a given range can be calculated in O(1) time. If there are many query operations and little updates, this works nicely.
Range total using a segment tree:
The most effective method is to utilise a segment tree; we can do both operations using a segment tree in O(log(N)) time.
Segment tree representation
Building a segment tree from the supplied array
We begin by examining the segment arr[0,... n-1]. And each time, we split the current segment in half (assuming it hasn't already become a segment of length 1), run the identical operation on both halves, and then store the result for each such segment in the appropriate node.
Except for the last level, every level of the created segment tree will be fully filled. Additionally, since we always break each segment into two at every level, the tree will be a Full Binary Tree. There will always be n-1 internal nodes because the created tree is always a full binary tree with n leaves. Consequently, there will be 2*n - 1 nodes overall.
How tall is the segment tree for the supplied array?
The segment tree will be log2N in height. The amount of memory allotted for the segment tree will be (2 * 2log2n-1) since the tree must be represented using an array and the relationship between the parent and child indexes must be preserved.
Search for the Sum of a Range
How to calculate the sum using the segment tree once it has been built. The algorithm to calculate the sum of the elements is as follows.
There are three situations in the aforementioned implementation that we need to address.
Update a value:
The update can be carried out recursively, just like tree building and query operations can. An outdated index has been provided to us. Let diff represent the new value. Beginning at the segment tree's root, we append diff to each node that has the specified index within its range. We don't modify a node if it doesn't have the specified index inside its range.
The application of the aforementioned strategy is seen below:
Sum of values in given range = 15 Updated sum of values in given range = 22