using
System;
using
System.Text;
class
TreeNode
{
public
int
val;
public
TreeNode left;
public
TreeNode right;
public
TreeNode(
int
x)
{
val = x;
left =
null
;
right =
null
;
}
}
class
Solution
{
public
TreeNode lca(TreeNode root,
int
startValue,
int
destValue)
{
if
(root ==
null
)
{
return
null
;
}
if
(root.val == startValue)
{
return
root;
}
if
(root.val == destValue)
{
return
root;
}
TreeNode l = lca(root.left, startValue, destValue);
TreeNode r = lca(root.right, startValue, destValue);
if
(l !=
null
&& r !=
null
)
{
return
root;
}
return
l !=
null
? l : r;
}
public
bool
getPath(TreeNode root,
int
value, StringBuilder path)
{
if
(root ==
null
)
{
return
false
;
}
if
(root.val == value)
{
return
true
;
}
path.Append(
"L"
);
bool
res = getPath(root.left, value, path);
if
(res)
{
return
true
;
}
path.Remove(path.Length - 1, 1);
path.Append(
"R"
);
res = getPath(root.right, value, path);
if
(res)
{
return
true
;
}
path.Remove(path.Length - 1, 1);
return
false
;
}
public
string
getDirections(TreeNode root,
int
startValue,
int
destValue)
{
root = lca(root, startValue, destValue);
StringBuilder p1 =
new
StringBuilder();
StringBuilder p2 =
new
StringBuilder();
getPath(root, startValue, p1);
getPath(root, destValue, p2);
for
(
int
i = 0; i < p1.Length; i++)
{
p1[i] =
'U'
;
}
return
p1.Append(p2).ToString();
}
}
public
class
Program
{
public
static
void
Main(
string
[] args)
{
TreeNode root =
new
TreeNode(5);
root.left =
new
TreeNode(1);
root.right =
new
TreeNode(2);
root.left.left =
new
TreeNode(3);
root.right.left =
new
TreeNode(6);
root.right.right =
new
TreeNode(4);
int
startValue = 3;
int
endValue = 6;
Solution solution =
new
Solution();
string
ans = solution.getDirections(root, startValue, endValue);
Console.WriteLine(ans);
}
}