using
System;
using
System.Collections.Generic;
public
class
Node
{
public
int
Start;
public
int
End;
public
Node Left;
public
Node Right;
public
Node(
int
s,
int
e)
{
Start = s;
End = e;
Left =
null
;
Right =
null
;
}
}
public
class
Program
{
public
static
Node CreateTree(HashSet<
int
> s)
{
List<
int
> values =
new
List<
int
>(s);
int
n = values.Count;
if
(n == 0)
return
null
;
Node root =
new
Node(values[0], values[0]);
Node curr = root;
for
(
int
i = 1; i < n; i++)
{
if
(values[i] == curr.End + 1)
{
curr.End = values[i];
}
else
{
Node node =
new
Node(values[i], values[i]);
if
(values[i] < curr.Start)
{
node.Right = curr;
curr = node;
}
else
{
Node parent = curr;
while
(parent.Right !=
null
&& values[i] > parent.Right.Start)
{
parent = parent.Right;
}
node.Left = parent.Right;
parent.Right = node;
}
curr = node;
}
}
return
root;
}
public
static
void
TraverseTreeAndInsert(Node node, HashSet<
int
> s)
{
if
(node ==
null
)
return
;
TraverseTreeAndInsert(node.Left, s);
for
(
int
i = node.Start; i <= node.End; i++)
{
s.Add(i);
}
TraverseTreeAndInsert(node.Right, s);
}
public
static
HashSet<
int
> MergeSets(HashSet<
int
> s1, HashSet<
int
> s2)
{
Node root1 = CreateTree(s1);
Node root2 = CreateTree(s2);
HashSet<
int
> result =
new
HashSet<
int
>();
TraverseTreeAndInsert(root1, result);
TraverseTreeAndInsert(root2, result);
DeleteNode(root1);
DeleteNode(root2);
return
result;
}
public
static
void
DeleteNode(Node node)
{
if
(node ==
null
)
return
;
DeleteNode(node.Left);
DeleteNode(node.Right);
node.Left =
null
;
node.Right =
null
;
}
public
static
void
Main(
string
[] args)
{
HashSet<
int
> s1 =
new
HashSet<
int
> { 1, 2, 3, 5, 6, 8, 9, 10 };
HashSet<
int
> s2 =
new
HashSet<
int
> { 4, 7, 11, 12 };
HashSet<
int
> result = MergeSets(s1, s2);
Console.WriteLine(
"The set after merging is:"
);
foreach
(
int
x
in
result)
{
Console.Write(x +
" "
);
}
}
}