我最近在http://www.geeksforgeeks.org/interval-tree/上完成了Interval树的实现,这里算法建议在每个子树上使用最大值。
找到重叠的算法如下:
Interval overlappingIntervalSearch(root, x)
1) If x overlaps with root's interval, return the root's interval.
2) 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
3) Else recur for right child.
我不明白为什么使用最大值, 它也可以通过比较间隔来获得LOG(N)结果。
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;
}
}
答案 0 :(得分:0)
max,例如使用此数据
{{15, 20}, {10, 11}, {17, 22}, {5, 20}, {12, 25}, {30, 40}};
并搜索24