using
System;
using
System.Collections.Generic;
public
class
Node {
public
int
Data
{
get
;
set
;
}
public
Node Left
{
get
;
set
;
}
public
Node Right
{
get
;
set
;
}
public
Node(
int
data)
{
this
.Data = data;
this
.Left =
null
;
this
.Right =
null
;
}
}
class
Program {
static
void
Print(Node parent)
{
Node curr = parent;
while
(curr !=
null
) {
Console.Write(curr.Data +
" "
);
curr = curr.Right;
}
}
static
void
Inorder(List<
int
> traversal, Node parent)
{
if
(parent ==
null
)
return
;
Inorder(traversal, parent.Left);
traversal.Add(parent.Data);
Inorder(traversal, parent.Right);
}
static
void
Form(
int
pos, List<
int
> traversal,
ref
Node prev)
{
if
(pos == traversal.Count)
return
;
prev.Right =
new
Node(traversal[pos]);
prev.Left =
null
;
prev = prev.Right;
Form(pos + 1, traversal,
ref
prev);
}
static
Node Flatten(Node parent)
{
Node dummy =
new
Node(-1);
Node prev = dummy;
List<
int
> traversal =
new
List<
int
>();
Inorder(traversal, parent);
Form(0, traversal,
ref
prev);
prev.Left =
null
;
prev.Right =
null
;
Node ret = dummy.Right;
return
ret;
}
static
void
Main(
string
[] args)
{
Node root =
new
Node(5);
root.Left =
new
Node(3);
root.Right =
new
Node(7);
root.Left.Left =
new
Node(2);
root.Left.Right =
new
Node(4);
root.Right.Left =
new
Node(6);
root.Right.Right =
new
Node(8);
Print(Flatten(root));
Console.ReadLine();
}
}