Segment Tree
Array Representation of Binary Tree
For a binary tree with n nodes, it can be represented by an array T .
- The index of
Tis from 1 to n,T[0]is empty - The root of the tree is located at
T[1] - The parent nodes are located at
T[:n//2+1] - The leaf nodes are located at
T[n//2+1:] - for
1 <= i <= n//2, its children are located atT[2*i]andT[2*i+1](may not exist) - for
2 <= i <= n, its parent node is located atT[i//2]
Implementation
Bottom Up
Single element update, range query, bottom up
for an array of length n, we need 2n space to store the segment tree, which contains 2n-1 values.
| Algorithm | Complexity |
|---|---|
| Space | |
| Construct | |
| Update | |
| Query |
Top Down
Range update, range query, lazy propagation, top down
for an array of length n, we need 2n space to store the segment tree, which contains 2n-1 values. Moreover, we need some space to cache the result of calculating the range of a given index.
| Algorithm | Complexity |
|---|---|
| Space | |
| Construct | |
| Update By Range | |
| Query |
