using
System;
using
System.Collections.Generic;
public
class
GFG {
public
class
TreeNode {
public
int
data;
public
TreeNode right;
public
TreeNode left;
public
TreeNode(
int
data) {
this
.data = data;
this
.left =
null
;
this
.right =
null
;
}
};
static
TreeNode insertNode(
int
data, TreeNode root) {
if
(root ==
null
) {
TreeNode node =
new
TreeNode(data);
return
node;
}
else
if
(data > root.data) {
root.right = insertNode(data, root.right);
}
else
if
(data <= root.data) {
root.left = insertNode(data, root.left);
}
return
root;
}
static
int
countNodes(TreeNode root) {
if
(root ==
null
)
return
0;
else
return
countNodes(root.left) + countNodes(root.right) + 1;
}
static
TreeNode toWaveList(TreeNode root) {
int
count = countNodes(root);
List<
int
> ans =
new
List<
int
>();
Stack<TreeNode> s1 =
new
Stack<TreeNode>();
Stack<TreeNode> s2 =
new
Stack<TreeNode>();
TreeNode root1 = root, root2 = root;
TreeNode curr1 =
null
, curr2 =
null
;
TreeNode head =
null
;
TreeNode temp =
null
;
int
l = 0;
while
(l++ < Math.Ceiling(count / 2.0)) {
while
(root1 !=
null
) {
s1.Push(root1);
root1 = root1.left;
}
curr1 = s1.Peek();
s1.Pop();
root1 = curr1.right;
while
(root2 !=
null
) {
s2.Push(root2);
root2 = root2.right;
}
curr2 = s2.Peek();
s2.Pop();
root2 = curr2.left;
if
(curr1.data == curr2.data) {
temp.right = curr1;
temp = temp.right;
break
;
}
if
(head ==
null
) {
head = curr1;
temp = curr1;
temp.right = curr2;
temp = temp.right;
}
else
{
temp.right = curr1;
temp = temp.right;
temp.right = curr2;
temp = temp.right;
}
}
temp.right =
null
;
temp = head;
while
(temp !=
null
) {
temp.left =
null
;
temp = temp.right;
}
return
head;
}
public
static
void
Main(String[] args) {
TreeNode root =
null
;
int
[]tree = { 1, 0, 10 };
for
(
int
i = 0; i < 3; i++) {
root = insertNode(tree[i], root);
}
TreeNode head = toWaveList(root);
while
(head !=
null
) {
Console.Write(head.data +
" "
);
head = head.right;
}
}
}