using
System;
class
Program {
static
void
Main(
string
[] args)
{
Node root = insert(
null
,
new
Interval(15, 20));
root = insert(root,
new
Interval(10, 30));
root = insert(root,
new
Interval(17, 19));
root = insert(root,
new
Interval(5, 20));
root = insert(root,
new
Interval(12, 15));
root = insert(root,
new
Interval(30, 40));
Console.WriteLine(
"Inorder traversal of constructed Interval Tree is"
);
inOrder(root);
Console.WriteLine();
Interval i =
new
Interval(6, 7);
Console.WriteLine(
"Searching for interval "
+ i);
Console.WriteLine(
"Overlaps with "
+ isOverlapping(root,
new
Interval(6, 7)));
}
public
class
Node {
public
Interval range;
public
Node left, right;
public
int
max;
public
Node(Interval range,
int
max)
{
this
.range = range;
this
.max = max;
}
public
override
string
ToString()
{
return
"["
+
this
.range.low +
", "
+
this
.range.high +
"] "
+
"max = "
+
this
.max +
"\n"
;
}
}
public
class
Interval {
public
int
low, high;
public
Interval(
int
low,
int
high)
{
this
.low = low;
this
.high = high;
}
public
override
string
ToString()
{
return
"["
+
this
.low +
","
+
this
.high +
"]"
;
}
}
public
static
Node insert(Node root, Interval x)
{
if
(root ==
null
) {
return
new
Node(x, x.high);
}
if
(x.low < root.range.low) {
root.left = insert(root.left, x);
}
else
{
root.right = insert(root.right, x);
}
if
(root.max < x.high) {
root.max = x.high;
}
return
root;
}
public
static
void
inOrder(Node root)
{
if
(root ==
null
) {
return
;
}
inOrder(root.left);
Console.Write(root);
inOrder(root.right);
}
public
static
Interval isOverlapping(Node root,
Interval x)
{
if
(root ==
null
) {
return
new
Interval(-1, -1);
}
if
((x.low > root.range.low
&& x.low < root.range.high)
|| (x.high > root.range.low
&& x.high < root.range.high)) {
return
root.range;
}
else
if
(root.left !=
null
&& root.left.max > x.low) {
return
isOverlapping(root.left, x);
}
else
{
return
isOverlapping(root.right, x);
}
}
}