using
System;
using
System.Collections.Generic;
class
Node
{
public
int
data;
public
Node right, down;
public
Node(
int
data)
{
this
.data = data;
right =
null
;
down =
null
;
}
}
class
pair
{
public
int
val;
public
Node head;
public
pair(Node head,
int
val)
{
this
.val = val;
this
.head = head;
}
}
class
pairComp : IComparer<pair>
{
public
int
Compare(pair p1, pair p2)
{
return
p1.val - p2.val;
}
}
class
PriorityQueue<T>
{
private
List<T> items =
new
List<T>();
private
IComparer<T> comparer;
public
PriorityQueue(IComparer<T> comparer)
{
this
.comparer = comparer;
}
public
void
Add(T item)
{
items.Add(item);
items.Sort(comparer);
}
public
bool
IsEmpty()
{
return
items.Count == 0;
}
public
T Poll()
{
T first = items[0];
items.RemoveAt(0);
return
first;
}
}
class
GFG
{
public
static
Node Flatten(Node root)
{
Node ptr = root;
Node h =
null
;
var
pq =
new
PriorityQueue<pair>(
new
pairComp());
while
(ptr !=
null
)
{
pq.Add(
new
pair(ptr, ptr.data));
ptr = ptr.right;
}
while
(!pq.IsEmpty())
{
Node temp = pq.Poll().head;
if
(temp.down !=
null
)
{
pq.Add(
new
pair(temp.down, temp.down.data));
}
if
(h ==
null
)
{
h = temp;
ptr = temp;
ptr.right =
null
;
}
else
{
ptr.down = temp;
ptr = temp;
ptr.right =
null
;
}
}
return
h;
}
public
static
Node push(Node head_ref,
int
data)
{
Node new_node =
new
Node(data);
new_node.down = head_ref;
head_ref = new_node;
return
head_ref;
}
public
static
void
printList(Node h)
{
while
(h !=
null
)
{
Console.Write(h.data +
" "
);
h = h.down;
}
}
public
static
void
Main(
string
[] args)
{
Node head =
null
;
head = push(head, 30);
head = push(head, 8);
head = push(head, 7);
head = push(head, 5);
head.right = push(head.right, 20);
head.right = push(head.right, 10);
head.right.right = push(head.right.right, 50);
head.right.right = push(head.right.right, 22);
head.right.right = push(head.right.right, 19);
head.right.right.right = push(head.right.right.right, 45);
head.right.right.right = push(head.right.right.right, 40);
head.right.right.right = push(head.right.right.right, 35);
head.right.right.right = push(head.right.right.right, 20);
head = Flatten(head);
printList(head);
}
}