class Node {
constructor(interval) {
this.interval = interval;
this.max = interval[1];
this.left = null;
this.right = null;
}
}
class IntervalTree {
constructor() {
this.root = null;
}
insert(root, interval) {
if (!root) {
return new Node(interval);
}
if (interval[0] < root.interval[0]) {
root.left = this.insert(root.left, interval);
} else {
root.right = this.insert(root.right, interval);
}
root.max = Math.max(root.max, interval[1]);
return root;
}
overlap(root, interval) {
if (!root) {
return null;
}
if (root.interval[0] <= interval[1] && root.interval[1] >= interval[0]) {
return root.interval;
}
if (root.left && root.left.max >= interval[0]) {
return this.overlap(root.left, interval);
}
return this.overlap(root.right, interval);
}
delete(root, interval) {
if (!root) {
return root;
}
if (interval[0] < root.interval[0]) {
root.left = this.delete(root.left, interval);
} else if (interval[0] > root.interval[0]) {
root.right = this.delete(root.right, interval);
} else {
if (!root.left) {
let temp = root.right;
root = null;
return temp;
} else if (!root.right) {
let temp = root.left;
root = null;
return temp;
}
let temp = this.minValueNode(root.right);
root.interval = temp.interval;
root.right = this.delete(root.right, temp.interval);
}
return root;
}
minValueNode(root) {
let current = root;
while (current.left !== null) {
current = current.left;
}
return current;
}
}
const intervals = [[15, 20], [10, 30], [17, 19], [5, 20], [12, 15], [30, 40]];
const IT = new IntervalTree();
for (const interval of intervals) {
IT.root = IT.insert(IT.root, interval);
}
const to_search = [25, 29];
console.log(`Searching for interval ${JSON.stringify(to_search)}`);
let res = IT.overlap(IT.root, to_search);
if (res) {
console.log(`Overlaps with ${JSON.stringify(res)}`);
} else {
console.log("No Overlapping Interval");
}
const to_erase = [10, 30];
console.log(`Deleting interval ${JSON.stringify(to_erase)}`);
IT.root = IT.delete(IT.root, to_erase);
console.log(`Searching for interval ${JSON.stringify(to_search)}`);
res = IT.overlap(IT.root, to_search);
if (res) {
console.log(`Overlaps with ${JSON.stringify(resultAfterDeletion)}`);
} else {
console.log("No Overlapping Interval");
}