using
System;
using
System.Collections.Generic;
public
class
Node {
public
int
data;
public
Node left, right;
public
bool
isThreaded;
public
Node(
int
item)
{
data = item;
left = right =
null
;
}
}
public
class
BinaryTree {
Node root;
void
populateQueue(Node node, Queue<Node> q)
{
if
(node ==
null
)
return
;
if
(node.left !=
null
)
populateQueue(node.left, q);
q.Enqueue(node);
if
(node.right !=
null
)
populateQueue(node.right, q);
}
void
createThreadedUtil(Node node, Queue<Node> q)
{
if
(node ==
null
)
return
;
if
(node.left !=
null
)
createThreadedUtil(node.left, q);
q.Dequeue();
if
(node.right !=
null
)
createThreadedUtil(node.right, q);
else
{
if
(q.Count != 0)
node.right = q.Peek();
node.isThreaded =
true
;
}
}
void
createThreaded(Node node)
{
Queue<Node> q =
new
Queue<Node>();
populateQueue(node, q);
createThreadedUtil(node, q);
}
Node leftMost(Node node)
{
while
(node !=
null
&& node.left !=
null
)
node = node.left;
return
node;
}
void
inOrder(Node node)
{
if
(node ==
null
)
return
;
Node cur = leftMost(node);
while
(cur !=
null
) {
Console.Write(
" "
+ cur.data +
" "
);
if
(cur.isThreaded ==
true
)
cur = cur.right;
else
cur = leftMost(cur.right);
}
}
public
static
void
Main(String[] args)
{
BinaryTree tree =
new
BinaryTree();
tree.root =
new
Node(1);
tree.root.left =
new
Node(2);
tree.root.right =
new
Node(3);
tree.root.left.left =
new
Node(4);
tree.root.left.right =
new
Node(5);
tree.root.right.left =
new
Node(6);
tree.root.right.right =
new
Node(7);
tree.createThreaded(tree.root);
Console.WriteLine(
"Inorder traversal of created threaded tree"
);
tree.inOrder(tree.root);
}
}