class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Function to find Lowest
// Common Ancestor (LCA)
function findLCA(root, p, q)
{
if (!root || root
.val === p || root
.val === q) return root;
const left = findLCA(root.left, p, q);
const right = findLCA(root.right, p, q);
if (left && right) return root;
return left ? left : right;
}
// Function to find distance
// between two nodes using LCA
function findDistanceOptimized(root, p, q) {
const lca = findLCA(root, p, q);
// Function to find distance
// from root to a given node
function findDepth(node, target, depth) {
if (!node) return 0;
if (node.val === target) return depth;
const left = findDepth(node.left, target, depth + 1);
const right = findDepth(node.right, target, depth + 1);
return left || right;
}
const distanceP = findDepth(lca, p, 0);
const distanceQ = findDepth(lca, q, 0);
return distanceP + distanceQ;
}
// Construct the binary tree
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.right = new TreeNode(6);
const node1 = 4;
const node2 = 6;
// Find distance between node1 and node2
// using optimized approach with LCA
console.log("Distance between",
node1, "and", node2, "using optimized approach with LCA is",
findDistanceOptimized(root, node1, node2));