using
System;
using
System.Collections.Generic;
public
class
GFG{
class
ListNode {
public
int
data;
public
ListNode next;
public
ListNode(
int
data)
{
this
.data = data;
this
.next =
null
;
}
};
class
TreeNode {
public
TreeNode left;
public
TreeNode right;
public
int
val;
public
TreeNode(
int
x){
left =
null
;
right =
null
;
val = x;
}
};
static
ListNode makeList(
int
[]arr,
int
n)
{
ListNode h =
null
;
ListNode root =
new
ListNode(0);
for
(
int
i = 0; i < n; i++) {
int
data = arr[i];
ListNode node =
new
ListNode(data);
if
(h ==
null
) {
h = node;
root = h;
}
else
{
root.next = node;
root = node;
}
}
return
h;
}
static
TreeNode build_tree(
int
[]nodes,
int
n)
{
TreeNode root =
new
TreeNode(nodes[0]);
Queue<TreeNode> q =
new
Queue<TreeNode>();
bool
is_left =
true
;
TreeNode cur =
null
;
q.Enqueue(root);
for
(
int
i = 1; i < n; i++) {
TreeNode node =
null
;
if
(nodes[i] != 0) {
node =
new
TreeNode(nodes[i]);
q.Enqueue(node);
}
if
(is_left) {
cur = q.Peek();
q.Dequeue();
cur.left = node;
is_left =
false
;
}
else
{
cur.right = node;
is_left =
true
;
}
}
return
root;
}
static
bool
findPath(TreeNode root, ListNode head,
List<
char
> path)
{
if
(root ==
null
) {
return
false
;
}
if
(root.val != head.data)
return
false
;
if
(root.left ==
null
&& root.right ==
null
&& head.next ==
null
) {
return
true
;
}
path.Add(
'L'
);
if
(findPath(root.left,
head.next, path))
return
true
;
path.RemoveAt(path.Count-1);
path.Add(
'R'
);
if
(findPath(root.right,
head.next, path))
return
true
;
path.RemoveAt(path.Count-1);
return
false
;
}
static
void
find(TreeNode root, ListNode head)
{
List<
char
> path =
new
List<
char
>();
findPath(root, head, path);
if
(path.Count == 0) {
Console.Write(
"-1"
);
return
;
}
for
(
int
i = 0;
i < path.Count; i++) {
Console.Write(path[i]+
" "
);
}
}
public
static
void
Main(String[] args)
{
int
[]tree = { 1, 2, 3, 4, 5, 6,
8, -1, -1, 8 };
TreeNode root = build_tree(tree, 10);
int
[]ll = { 1, 2, 5, 8 };
ListNode head = makeList(ll, 4);
find(root, head);
}
}