class Node {
constructor(key) {
this
.key = key;
this
.left =
null
;
this
.right =
null
;
}
}
function
newNode(key) {
const temp =
new
Node(key);
return
temp;
}
function
findPath(root, d, str, s) {
if
(root ===
null
)
return
;
if
(root.key === d) {
s.value = str;
return
;
}
findPath(root.left, d, str +
"l"
, s);
findPath(root.right, d, str +
"r"
, s);
}
function
findLCAUtil(root, n1, n2, v1, v2) {
if
(root ===
null
)
return
null
;
if
(root.key === n1) {
v1.value =
true
;
return
root;
}
if
(root.key === n2) {
v2.value =
true
;
return
root;
}
const left_lca = findLCAUtil(root.left, n1, n2, v1, v2);
const right_lca = findLCAUtil(root.right, n1, n2, v1, v2);
if
(left_lca && right_lca)
return
root;
return
left_lca !==
null
? left_lca : right_lca;
}
function
find(root, x) {
if
(root ===
null
)
return
false
;
if
(root.key === x || find(root.left, x) || find(root.right, x))
return
true
;
return
false
;
}
function
findLCA(root, first, second) {
const v1 = { value:
false
};
const v2 = { value:
false
};
const lca = findLCAUtil(root, first, second, v1, v2);
if
((v1.value && v2.value) || (v1.value && find(lca, second)) || (v2.value && find(lca, first)))
return
lca;
return
null
;
}
function
NumberOFTurns(root, first, second) {
if
(root ===
null
|| first === second)
return
0;
const s1 = { value:
""
};
const s2 = { value:
""
};
const lca = findLCA(root, first, second);
findPath(lca, first,
""
, s1);
findPath(lca, second,
""
, s2);
if
(s1.value.length === 0 && s2.value.length === 0)
return
-1;
s1.value = s1.value.split(
""
).reverse().join(
""
);
s1.value += s2.value;
let cnt = 0;
let flag =
false
;
for
(let i = 0; i < s1.value.length - 1; i++) {
if
(s1.value[i] !== s1.value[i + 1]) {
flag =
true
;
cnt += 1;
}
}
if
(!flag)
return
-1;
return
cnt;
}
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.right.left.left = newNode(9);
root.right.left.right = newNode(10);
let turn = 0;
if
((turn = NumberOFTurns(root, 5, 10))!=-1)
console.log(turn);
else
console.log(
"Not Possible"
);