Repository navigation
Expand file tree
/
Copy pathIntervalTree.java
More file actions
84 lines (72 loc) · 2.26 KB
/
Copy pathIntervalTree.java
File metadata and controls
84 lines (72 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.interview.tree;
/**
* Date 11/07/2015
* @author Tushar Roy
*
* Write class for interval tree
* Keep a max at every node which is max of that subtree.
* This max is used to decide which direction to move when checking
* for overlap. When an interval's high is less than max of left side go
* in that direciton otherwise go in other direction.
*/
class InternalNode {
int low;
int high;
int max;
InternalNode left;
InternalNode right;
@Override
public String toString() {
return "InternalNode{" +
"max=" + max +
", low=" + low +
", high=" + high +
'}';
}
}
public class IntervalTree {
public InternalNode insert(InternalNode root, int low, int high) {
if(root == null) {
InternalNode node = new InternalNode();
node.low = low;
node.high = high;
node.max = high;
return node;
}
if(low < root.low) {
root.left = insert(root.left, low, high);
} else {
root.right = insert(root.right, low, high);
}
root.max = Math.max(root.high, high);
return root;
}
public InternalNode isOverlap(InternalNode root, int low, int high) {
if(root == null) {
return null;
}
if(root.high >= low && root.low <= high) {
return root;
}
if(root.left != null && root.left.max > low) {
return isOverlap(root.left, low, high);
} else {
return isOverlap(root.right, low, high);
}
}
public static void main(String args[]) {
IntervalTree it = new IntervalTree();
InternalNode root = null;
root = it.insert(root, 10, 15);
root = it.insert(root, 11, 13);
root = it.insert(root, 18, 21);
root = it.insert(root, 20, 25);
root = it.insert(root, 0, 7);
System.out.println(it.isOverlap(root, 8, 9));
System.out.println(it.isOverlap(root, 17, 17));
System.out.println(it.isOverlap(root, 21, 22));
System.out.println(it.isOverlap(root, 21, 22));
System.out.println(it.isOverlap(root, 12, 18));
System.out.println(it.isOverlap(root, 24, 26));
}
}