-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntervalTree.java
More file actions
114 lines (100 loc) · 2.95 KB
/
IntervalTree.java
File metadata and controls
114 lines (100 loc) · 2.95 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package IntervalTrees;
import java.util.Arrays;
public class IntervalTree {
Node root;
int[][] intervals;
public IntervalTree(int[][] intervals){
this.intervals = intervals;
int[] i = intervals[0];
root = new Node(i[0], i[1]);
construct();
}
public void construct(){//returns root
for (int i = 1; i < intervals.length; i++){
int[] borders = intervals[i];
//borders[0] = low, borders[1] = high
addNode(borders[0], borders[1]);
}
}
public void addNode(int low, int high){
boolean added = false;
Node node = root;
while (!added){
node.setMax(high);
if (node.low > low){
if (node.left != null){
node = node.left;
}else {
node.left = new Node(low, high);
added = true;
}
}else {
if (node.right != null){
node = node.right;
}else {
node.right = new Node(low, high);
added = true;
}
}
}
}
public void traverse(Node node){
if (node == null){
return;
}
// System.out.println("low : " + node.low + ", high : " + node.high);
traverse(node.left);
System.out.println("[ " + node.low + ", " + node.high + " ] max : " + node.max);
traverse(node.right);
}
public int[] search(int[] borders){
Node node = root;
int low = borders[0];
int high = borders[1];
int[] intervals = new int[2]; // it will contains node intervals
while (node != null){
if (define(node, low, high)){
intervals[0] = node.low;
intervals[1] = node.high;
return intervals;
}else {
if (node.high < low){
node = node.right;
}else if (node.low > high){
node = node.left;
}
}
}
return null;
}
public boolean define(Node node, int low, int high){
if (node.low < low && node.high > high){
return true;
}else if (node.low > low && node.low < high){
return true;
}
if (node.high > low && node.high < high){
return true;
}else return node.low > low && node.low < high;
}
}
class Node{
public int high;
public int low;
public int max;
public Node left;//left child
public Node right;//right child
//low and high borders of the interval
// max - max value in the given interval
public Node(int low, int high){
this.low = low;
this.high = high;
this.max = high;
right = left = null;
}
public void setMax(int max) {
if (this.max < max) {
this.max = max;
}
}
}