I have implemented an Interval Tree in Java as outlined in the CLRS algorithm book (it uses red-black tree as the underlying structure). In the book (and as far as I've seen online), it discusses how to find the node whose interval contains the number being queried.
In my case, if the number being queried does not fall into any interval, I want to know what the 'closest' nodes are, i.e., those whose intervals lie immediately before and immediately after the query. I have accomplished this using the following functions. Each node contains the interval (int low, int high), as well as the min and max values of themselves and their subtrees.
public Node[] findPrevNext(int query) {
if (tree.root.isNull())
return null;
else {
Node prev = findPrev(query, tree.root, new Node());
Node next = findNext(query, tree.root, new Node());
Node[] result = {prev, next};
return result;
}
}
private Node findPrev(int query, Node x, Node prev) {
if (x.interval.high < query && x.interval.high > prev.interval.high)
prev = x;
if (!x.left.isNull())
prev = findPrev(query, x.left, prev);
if (!x.right.isNull())
prev = findPrev(query, x.right, prev);
return prev;
}
private Node findNext(int query, Node x, Node next) {
if (x.interval.low > query && x.interval.low < next.interval.low)
next = x;
if (!x.left.isNull())
next = findNext(query, x.left, next);
if (!x.right.isNull())
next = findNext(query, x.right, next);
return next;
}
The problem, of course, is that the functions findPrev() and findNext() both traverse the whole tree and don't take advantage of the tree's structure. Is there a way to perform this query in O(lgn) time?
I've also considered the possibility of creating a second Interval Tree which would contain all interval gaps, and simply doing the query on there. The nodes would then contain information about which elements are before and after that gap (I have attempted but as of yet am unsuccessful in implementing this).
Edit: Just to note, the function findPrevNext() is called after attempting to find the query fails. So, the query is known not to fall in any given interval beforehand.