Constructing the segment tree

There are two important points to be noted while constructing the segment tree:

  • Choosing what value to be stored in the nodes according to the problem definition
  • What should the merge operation do

If the problem definition states that we need to calculate the sum over ranges, then the value at nodes should store the sum of values over the ranges.

  • The child node values are merged back into the parent node to hold the value for that particular range, [i.e., the range covered by all the nodes of its subtree]. 
  • In the end, leaf nodes store information about a single element. All the leaf nodes store the array based on which the segment tree is built. 

Following are the steps for constructing a segment tree:

  1. Start from the leaves of the tree
  2. Recursively build the parents from the merge operation

The merge operation will take constant time if the operator takes constant time. SO building the whole tree takes O(N) time.

Segment tree

Introduction to Segment Trees – Data Structure and Algorithm Tutorials

Similar Reads

What is Segment Tree?

A Segment Tree is a data structure that stores information about a range of elements in its nodes. It also allows users to modify the array and perform range queries in smaller complexity. For example, we can perform a range summation of an array between the range L to R while also modifying the array from range L to R all in log(N) time complexity....

Types of Operations:

The operations that the segment tree can perform must be binary and associative. Overall the values must belong to the set of the semigroup. The neutral element must be obvious according to the type of operation and semigroup we are looking for. For example, if we want to find the sum over the range of values in an array where the elements belong to  then the neutral element, in this case, will be 0. Some of the examples of operations are:...

Structure of the Tree

The segment tree works on the principle of divide and conquer....

Constructing the segment tree:

There are two important points to be noted while constructing the segment tree:...

Range Query

Let us understand this with the help of the following problem...

Point Updates

Given an index,  idx, update the value of the array at index idx with value V...

Updating an interval (Lazy propagation):

...

Applications:

...

Advantages:

...

Disadvantages:

...

Contact Us