I recently went through the implementation of Interval tree on http://www.geeksforgeeks.org/interval-tree/, Here the algorithm suggests to use a max value at each subtree.
And the algo for finding overlap is as:
Interval overlappingIntervalSearch(root, x)
If x overlaps with root's interval, return the root's interval.
If left child of root is not empty and the max in left child is greater than x's low value, recur for left child
Else recur for right child.
What I don't understand is why use a max value, it can be done by comparing the intervals also to get a LOG(N) result.
public class IntervalTree {
private Node ROOT;
private class Node {
Point data;
Node left, right;
public Node(Point data) {
this.data = data;
}
}
public static void main(String... args) throws IOException {
new IntervalTree().task();
}
private void task() {
insert();
Node pop = findInterval(ROOT, new Node(new Point(6,7)));
if (pop != null) System.out.println(pop.data.toString());
else System.out.println("No overlap");
}
private Node findInterval(Node root, Node node) {
if (root == null) return null;
if (overlap(root.data, node.data)) return root;
else if (node.data.x < root.data.x) return findInterval(root.left, node);
return findInterval(root.right, node);
}
private boolean overlap(Point one, Point two) {
return two.x <= one.y && one.x <= two.y;
}
private void insert() {
int data[][] = new int[][]{{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40}};
for (int i = 0; i < data.length; i++)
ROOT = insert(data[i]);
}
private Node insert(int[] pt) {
return insert(ROOT, new Node(new Point(pt[0], pt[1])));
}
private Node insert(Node root, Node node) {
if (root == null) return node;
else if (node.data.x < root.data.x)
root.left = insert(root.left, node);
else root.right = insert(root.right, node);
return root;
}
}
max is needed to find the overlap, eg use this data
{{15, 20}, {10, 11}, {17, 22}, {5, 20}, {12, 25}, {30, 40}};
and search for 24