algorithm-notes
  • Preface
  • Outline
    • Asymptotic-Analysis
    • Divide-and-Conquer (DnC)
      • Overview
      • Multiplication
      • DnC Strategy
      • Master Method
    • Randomization
      • Overview
      • Discrete Probability
      • Randomized Algorithms
      • Reservoir Sampling
    • Sorting
      • Overview
      • Selection Sort
      • Bubble Sort
      • Insertion Sort
      • Shell Sort
      • Merge Sort
      • Heap Sort
      • Quick Sort
      • Non-Comparison Sort
    • Graph Algorithms
      • Overview
      • Minimum Spanning Tree
      • Shortest Path
      • Topological Sort
    • Tree
      • Overview
      • Balanced Search Tree
        • AVL Tree
        • Red-Black Tree
        • B Tree
      • Heap
      • Disjoint Set
      • Threaded Binary Tree
      • Segment Tree
    • Searching
      • Overview
      • Binary Search
      • Graph Search
      • Hash Table
      • String Search
    • Dynamic Programming
      • Overview
      • Fibonacci Numbers
      • LCS problem
    • Greedy Algorithms
      • Overview
Powered by GitBook
On this page

Was this helpful?

  1. Outline
  2. Tree

Segment Tree

PreviousThreaded Binary TreeNextSearching

Last updated 6 years ago

Was this helpful?

Segment tree is a contextual binary tree designed for storing intervals or segments of a series of data items to speed up specific queries such as . Being contextual, each node of the segment tree represents an interval of data indices. Consider the following example:

An array of integers INPUT of size N, build a segment tree T which has:

  1. The root of T represents the data to be queried within interval INPUT[0...N-1]

  2. Leaves represent a single element INPUT[i] where 0 <= i < N.

  3. The internal nodes in level h of T represents 2h number of nodes, each have data to be queried from interval from INPUT[i...j], where 0 <= i < j < N

There are N leaves in T and N - 1 internal nodes. Thus, the total number of nodes is 2 ⋅ N - 1. When the segment tree is built, its structure cannot be changed.

Figure 1. A Segment Tree Built on an Array of size 7

There are two operations that can be performed on a segment tree:

  1. update: given an index and a value within the array, update the corresponding element. The time complexity is Ο(log N) time.

  2. query: given index l and r, return the contextual value within the interval from l to r. (e.g. the minimal value within the range). In average, each query takes Ο(log N) time.

Range Minimum Query