using
System;
using
System.Collections.Generic;
class
GFG{
public
class
Node {
public
int
val;
public
Node left=
null
, right=
null
;
public
List<Node> child =
new
List<Node>();
}
static
Node newNode(
int
key)
{
Node temp =
new
Node();
temp.val = key;
return
temp;
}
static
int
flag;
static
void
findPath(Node root,
int
key,
List<
int
> arr)
{
if
(root==
null
)
return
;
arr.Add(root.val);
if
(root.val == key) {
flag = 1;
return
;
}
for
(
int
i = 0; i < root.child.Count; i++) {
findPath(root.child[i], key, arr);
if
(flag == 1)
return
;
}
arr.RemoveAt(arr.Count-1);
return
;
}
static
void
findMinDist(Node root,
int
A,
int
B)
{
if
(root ==
null
)
return
;
int
val = root.val;
List<
int
> arr1 =
new
List<
int
>();
List<
int
> arr2 =
new
List<
int
>();
flag = 0;
findPath(root, A, arr1);
flag = 0;
findPath(root, B, arr2);
int
j=0;
for
(
int
i = 1; i < Math.Min(arr1.Count, arr2.Count); i++) {
if
(arr1[i] != arr2[i]) {
val = arr1[i - 1];
j = i - 1;
break
;
}
}
int
d1 = 0, d2 = 0;
for
(
int
i = j; i < arr1.Count; i++)
if
(arr1[i] == A)
break
;
else
d1 += 1;
for
(
int
i = j; i < arr2.Count; i++)
if
(arr2[i] == B)
break
;
else
d2 += 1;
val = d1 + d2;
Console.WriteLine(val);
}
public
static
void
Main()
{
Node root = newNode(1);
(root.child).Add(newNode(2));
(root.child).Add(newNode(3));
(root.child[0].child).Add(newNode(4));
(root.child[0].child).Add(newNode(5));
(root.child[1].child).Add(newNode(6));
(root.child[1]).child.Add(newNode(7));
(root.child[1].child).Add(newNode(8));
int
A = 4, B = 3;
findMinDist(root, A, B);
}
}