Find the Distance Between Two Nodes in the Binary Tree using JavaScript
Last Updated :
18 Jun, 2024
Given two nodes, our task is to find the distance between two nodes in a binary tree using JavaScript, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another.

Examples:
Input: Binary Tree as described above in diagram, n1 = 42
, n2 = 52
Output: Distance between nodes 42 and 52 is 2.
Below are ways by which we can find the distance between two nodes in the binary tree using JavaScript:
Using Lowest Common Ancestor (LCA)
In this approach, we find the LCA of the two given nodes first and then calculate the distance from the LCA to each of the two nodes. The sum of these two distances will give the distance between the nodes.
- Find LCA by Traversing the tree of the two given nodes
- Calculate the distance from the LCA to each of the two nodes.
- The distance between the two nodes is the sum of the two distances from the LCA to the nodes.
Example: We are using Lowest Common Ancestor (LCA) to find the distance between two nodes in the binary tree.
JavaScript
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)}`);
OutputDistance between nodes 42 and 52 is 2
Time Complexity: O(N) where N is the number of nodes in the tree.
Space Complexity: O(H) where H is the height of the tree.
Using Path Finding Method
In this approach, we find the paths from the root to each of the two nodes. Then, we find the longest common prefix of these two paths. The distance between the two nodes is the total length of the paths minus twice the length of the common prefix.
- Find the paths from the root to each of the two nodes.
- Determine the longest common prefix of these two paths.
- The distance between the two nodes is the total length of the paths minus twice the length of the common prefix.
Example: In this example we are using Path Finding Method to find the distance between two nodes in the binary tree .
JavaScript
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
// Helper function to find the path
// from the root to a given node
function findPath(root, path, k) {
if (root === null) {
return false;
}
// Append current node's value to the path
path.push(root.val);
// Check if the current node is the desired node
if (root.val === k) {
return true;
}
// Recursively check left and right subtrees
if ((root.left && findPath(root.left, path, k))
|| (root.right && findPath(root.right, path, k))) {
return true;
}
// If not found, remove
// current node's value from path
path.pop();
return false;
}
// Main function to find the distance between two nodes
function findDistancePathMethod(root, n1, n2) {
if (root === null) {
return 0;
}
const path1 = [];
const path2 = [];
// Find paths from root to n1 and n2
if (!findPath(root, path1, n1) || !findPath(root, path2, n2)) {
return -1;
}
// Find the longest common prefix
let i = 0;
while (i < path1.length && i < path2.length) {
if (path1[i] !== path2[i]) {
break;
}
i++;
}
// Calculate the distance
return (path1.length + path2.length - 2 * i);
}
// 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 ${findDistancePathMethod(root, n1, n2)}`);
OutputDistance between nodes 42 and 52 is 2
Time Complexity: O(N), where N is the number of nodes in the tree.
Space Complexity: O(H), where H is the height of the tree.