AVL IntervalTree
AVL IntervalTree
Muralidhara V N
IIIT Bangalore
Dynamic Collection of Intervals
• Add(Interval)
• Delete(Interval)
• Overlap(Interval) – does it overlap
with any one of the intervals in the
collection ?
26 39 50 58
1 9 12 17 20 32 40 60
Law of Trichotomy
Given any two intervals [l(a),h(a)] and
[l(b),h(b)], exactly one of the following
should hold.
• A is to the left of B: h(a) < l(b)
A B
Law of Trichotomy
Given any two intervals [l(a),h(a)] and
[l(b),h(b)], exactly one of the following
should hold.
• A is to the left of B: h(a) < l(b)
A B
60 20
17 12 40 60
9 1
39
26 50 58
26 39 50 58
1 9 12 17 20 32 40 60
BBST Structure
struct BST
{
long long int key;
int height;
long long int max, high;
struct BST *left, *right;
};
Max of a node
node->left->max
node->max=Max node->high
node->right-
>max
Updatemax
Void Updatemax (struct BST *node){
if (node)
{
node->max = node->high;
60 20
17 12 40 60
9 1
39
26 50 58
26 39 50 58
1 9 12 17 20 32 40 60
Overlap in O(log n)
struct BST * Overlap (struct BST *node, long long int l, long long int
r) {
while (node){
if (l <= node->high && node->key <= r) return node;
elsenode = node->right;
}
return NULL;
}
Correctness of Overlap
• If we go to the right and did not find any overlap,
then the interval can not overlap with any
interval on the left side.
• when to the right because max on left < l, implies for
any interval on the left side h(a)<l
l r
l(a) h(a) l(b) h(b)
Interval Trees in O(log n)
• Add()
• Delete()
• Overlap()