using
System;
using
System.Collections.Generic;
namespace
HelloWorld {
public
class
Node {
public
int
key;
public
Node left, right;
}
public
class
Program {
public
static
Node newNode(
int
key)
{
Node node =
new
Node();
node.key = key;
node.left = node.right =
null
;
return
node;
}
public
static
List<List<
int
> >
printVerticalOrder(Node root)
{
SortedDictionary<
int
, SortedDictionary<
int
, SortedSet<
int
> > >
mpp =
new
SortedDictionary<
int
,
SortedDictionary<
int
, SortedSet<
int
> > >();
Queue<Tuple<Node, Tuple<
int
,
int
> > > q
=
new
Queue<Tuple<Node, Tuple<
int
,
int
> > >();
q.Enqueue(
new
Tuple<Node, Tuple<
int
,
int
> >(
root,
new
Tuple<
int
,
int
>(0, 0)));
while
(q.Count > 0) {
var
p = q.Dequeue();
Node temp = p.Item1;
int
vertical = p.Item2.Item1;
int
level = p.Item2.Item2;
if
(!mpp.ContainsKey(vertical)) {
mpp[vertical] =
new
SortedDictionary<
int
, SortedSet<
int
> >();
}
if
(!mpp[vertical].ContainsKey(level)) {
mpp[vertical][level] =
new
SortedSet<
int
>();
}
mpp[vertical][level].Add(temp.key);
if
(temp.left !=
null
)
q.Enqueue(
new
Tuple<Node, Tuple<
int
,
int
> >(
temp.left,
new
Tuple<
int
,
int
>(vertical - 1,
level + 1)));
if
(temp.right !=
null
)
q.Enqueue(
new
Tuple<Node, Tuple<
int
,
int
> >(
temp.right,
new
Tuple<
int
,
int
>(vertical + 1,
level + 1)));
}
List<List<
int
> > ans =
new
List<List<
int
> >();
foreach
(
var
p
in
mpp)
{
List<
int
> col =
new
List<
int
>();
foreach
(
var
qItem
in
p.Value)
{
col.AddRange(qItem.Value);
}
ans.Add(col);
}
return
ans;
}
static
void
Main(
string
[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(11);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.left.right = newNode(8);
root.right.right.right = newNode(9);
List<List<
int
> > v = printVerticalOrder(root);
foreach
(
var
i
in
v)
{
foreach
(
var
j
in
i) { Console.Write(j +
" "
); }
Console.WriteLine();
}
}
}
}