using
System;
using
System.Collections.Generic;
public
class
PrintPath
{
public
static
void
printTopToBottomPath(Node curr,
Dictionary<Node,Node> parent)
{
Stack<Node> stk =
new
Stack<Node>() ;
while
(curr !=
null
)
{
stk.Push(curr);
curr = parent[curr];
}
while
(stk.Count != 0)
{
curr = stk.Pop();
Console.Write(curr.data +
" "
);
}
Console.WriteLine();
}
public
static
void
printRootToLeaf(Node root)
{
if
(root ==
null
)
return
;
Stack<Node> nodeStack =
new
Stack<Node>();
nodeStack.Push(root);
Dictionary<Node,Node> parent =
new
Dictionary<Node,Node>();
parent.Add(root,
null
);
while
(nodeStack.Count != 0)
{
Node current = nodeStack.Pop();
if
(current.left ==
null
&& current.right ==
null
)
printTopToBottomPath(current, parent);
if
(current.right !=
null
)
{
parent.Add(current.right,current);
nodeStack.Push(current.right);
}
if
(current.left !=
null
)
{
parent.Add(current.left,current);
nodeStack.Push(current.left);
}
}
}
public
static
void
Main(String []args)
{
Node root =
new
Node(10);
root.left =
new
Node(8);
root.right =
new
Node(2);
root.left.left =
new
Node(3);
root.left.right =
new
Node(5);
root.right.left =
new
Node(2);
printRootToLeaf(root);
}
}
public
class
Node
{
public
int
data;
public
Node left, right;
public
Node(
int
data)
{
left = right =
null
;
this
.data = data;
}
};