using
System;
using
System.Collections.Generic;
class
Solution
{
public
class
Node
{
public
int
data;
public
Node left, right;
}
static
Node getNode(
int
data)
{
Node newNode =
new
Node();
newNode.data = data;
newNode.left = newNode.right =
null
;
return
newNode;
}
static
Boolean getPath(Node root, List<
int
> arr,
int
x)
{
if
(root ==
null
)
return
false
;
arr.Add(root.data);
if
(root.data == x)
return
true
;
if
(getPath(root.left, arr, x) || getPath(root.right, arr, x))
return
true
;
arr.RemoveAt(arr.Count-1);
return
false
;
}
static
void
printPathBetweenNodes(Node root,
int
n1,
int
n2)
{
List<
int
> path1 =
new
List<
int
>();
List<
int
> path2 =
new
List<
int
>();
getPath(root, path1, n1);
getPath(root, path2, n2);
int
intersection = -1;
int
i = 0, j = 0;
while
(i != path1.Count || j != path2.Count)
{
if
(i == j && path1[i] == path2[i])
{
i++;
j++;
}
else
{
intersection = j - 1;
break
;
}
}
for
( i = path1.Count - 1; i > intersection; i--)
Console.Write( path1[i] +
" "
);
for
( i = intersection; i < path2.Count; i++)
Console.Write( path2[i] +
" "
);
}
public
static
void
Main(String[] args)
{
Node root = getNode(0);
root.left = getNode(1);
root.left.left = getNode(3);
root.left.left.left = getNode(7);
root.left.right = getNode(4);
root.left.right.left = getNode(8);
root.left.right.right = getNode(9);
root.right = getNode(2);
root.right.left = getNode(5);
root.right.right = getNode(6);
int
node1 = 7;
int
node2 = 4;
printPathBetweenNodes(root, node1, node2);
}
}