Organization of a Segment Tree
A segment tree is a binary tree where each node represents the interval or segment of the array. The root of the segment tree represents the entire array and each leaf represents the single element of an array. Internal nodes represent the union of the children intervals.
Representation of Segment Tree:
- Let us consider the array [ 1, 3, 5, 7, 9, 11 ]
Explanation of the Image:
Leaf Nodes are represent the individual elements of an array. Leaf Nodes are :
- [0, 0] represent the first element of the array i.e. 1.
- [1, 1] represent the first element of the array i.e. 3.
- [2, 2] represent the first element of the array i.e. 5.
- [3, 3] represent the first element of the array i.e. 7.
- [4, 4] represent the first element of the array i.e. 9.
- [5, 5] represent the first element of the array i.e. 11.
Internal Nodes are represent the sum of their children. Internal Nodes are:
- [0, 1] represent the sum of the elements 1 and 3.
- [0, 2] represent the sum of the elements 1, 3 and 5.
- [0, 3] represent the sum of the elements 7 and 9.
- [0, 4] represent the sum of the elements 7, 9 and 11.
- [0, 5] represent the sum of all the elements in the array.
Segment Tree in Java
A Segment Tree is a binary tree used for storing intervals or segments. It is allowed to query sum, minimum, maximum or other associative operations over the range of elements in the array efficiently. Each node in the segment tree represents the interval of an array. Leaves of the segment tree corresponding to the individual elements of an array. Each internal nodes is store information such as sum, minimum, and maximum about the segment that union of its children segments.
Segment trees are particularly useful in scenarios where multiple range queries and updates on the array, provide an efficient way to perform these operations with the logarithmic time complexity.