class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
// Helper function to find
// the LCA of two nodes
function findLCA(root, n1, n2) {
if (root === null) {
return null;
}
if (root.val === n1 || root.val === n2) {
return root;
}
const leftLCA = findLCA(root.left, n1, n2);
const rightLCA = findLCA(root.right, n1, n2);
if (leftLCA !== null && rightLCA !== null) {
return root;
}
return (leftLCA !== null) ? leftLCA : rightLCA;
}
// Helper function to find the
// distance from the LCA to a given node
function findDistanceFromLCA(lca, k, dist) {
if (lca === null) {
return -1;
}
if (lca.val === k) {
return dist;
}
const leftDist = findDistanceFromLCA(lca.left, k, dist + 1);
if (leftDist !== -1) {
return leftDist;
}
return findDistanceFromLCA(lca.right, k, dist + 1);
}
// Main function to find the
// distance between two nodes
function findDistance(root, n1, n2) {
const lca = findLCA(root, n1, n2);
const d1 = findDistanceFromLCA(lca, n1, 0);
const d2 = findDistanceFromLCA(lca, n2, 0);
return d1 + d2;
}
// Example usage
const root = new TreeNode(12);
root.left = new TreeNode(22);
root.right = new TreeNode(32);
root.left.left = new TreeNode(42);
root.left.right = new TreeNode(52);
root.right.left = new TreeNode(62);
root.right.right = new TreeNode(72);
const n1 = 42, n2 = 52;
console.log(`Distance between nodes ${n1} and
${n2} is ${findDistance(root, n1, n2)}`);