Segment Trees Flashcards
1
Q
Segment Tree
A
- Binary tree
- Each element in original array is leaf of binary tree
- Allows you to ask questions about a range of indices in an array
- static data strcture – cannot be modified once built
2
Q
Segment Tee
Construction
A
- Elements of array should become leaves of tree
- Root is minimum of entire range
- Represented implicity with array (like binary heap)
Steps
- Split array into halves recursively into array is size 2 and 1
- Bubble up, recording minimums of elements in pairs
- Create segment tree array using formula:
- If array size is power of 2
size*2 - 1
If not
Find next power of 2
num*2 - 1
- Initialize segment tree array to inf
Time: O(n)
Space: O(n)
3
Q
Segment Tree
Searching
A
- Describes the overlap of the query interval to the node itnervals
3 conditions
- Total overlap
- Node interval fits completely inside query interval
- Stop, return value at node
- No overlap/disjoint
- Node interval and query interval are disjoint
- Return max (really big number)
- Partial overlap
- Node interval not completely inside query interval
- Basically not 1 or 2
- Must check both sides
OlogN
4
Q
Segment Tree
Size
A
- If array size is power of 2
- size*2 - 1
- If not
- Find next power of 2
- num*2 - 1
*
5
Q
Segment Tree
range query
A
*
6
Q
Segment Tree
Lazy Propagation
A
- Increase the size of a range by increasing nodes
- Propogation only happens when nodes are visited
Steps
- Find range nodes like normal
- Increase val at node
- Increase val during recursive return