using
System;
using
System.Collections;
using
System.Collections.Generic;
using
System.Linq;
class
Node {
public
int
data;
public
Node left;
public
Node right;
public
Node(
int
val){
data = val;
left =
null
;
right =
null
;
}
}
class
HelloWorld {
public
static
int
findMinTime(Node root,
int
target,
int
level, Dictionary<
int
, List<
int
>> ans,
int
consider)
{
if
(root ==
null
)
return
-1;
if
(consider == 1) {
if
(ans.ContainsKey(level) ==
false
){
ans.Add(level,
new
List<
int
>());
}
ans[level].Add(root.data);
}
if
(root.data == target) {
if
(ans.ContainsKey(0) ==
false
){
ans.Add(0,
new
List<
int
>());
}
ans[0].Add(root.data);
findMinTime(root.left, target, 1, ans, 1);
findMinTime(root.right, target, 1, ans, 1);
return
1;
}
int
left = findMinTime(root.left, target, level + 1, ans, consider);
int
right = findMinTime(root.right, target, level + 1, ans, consider);
if
(left != -1) {
if
(ans.ContainsKey(left) ==
false
){
ans.Add(left,
new
List<
int
>());
}
ans[left].Add(root.data);
findMinTime(root.right, target, left + 1, ans, 1);
return
left + 1;
}
if
(right != -1) {
if
(ans.ContainsKey(right) ==
false
){
ans.Add(right,
new
List<
int
>());
}
ans[right].Add(root.data);
findMinTime(root.left, target, right + 1, ans, 1);
return
right + 1;
}
return
-1;
}
public
static
Dictionary<
int
, List<
int
>> minTime(Node root,
int
target)
{
Dictionary<
int
, List<
int
>> ans =
new
Dictionary<
int
, List<
int
>>();
int
res = findMinTime(root, target, 0, ans, 0);
return
ans;
}
static
void
Main() {
Node root =
new
Node(10);
root.left =
new
Node(12);
root.right =
new
Node(13);
root.right.left =
new
Node(14);
root.right.right =
new
Node(15);
root.right.left.left =
new
Node(21);
root.right.left.right =
new
Node(22);
root.right.right.left =
new
Node(23);
root.right.right.right =
new
Node(24);
int
targetNode = 14;
Dictionary<
int
, List<
int
>> answer = minTime(root, targetNode);
foreach
(KeyValuePair<
int
, List<
int
>> it
in
answer.Reverse())
{
Console.Write(
"Nodes burnt at stage "
+ it.Key +
" are "
);
foreach
(
var
i
in
it.Value){
Console.Write(i +
" "
);
}
Console.WriteLine();
}
}
}