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.
Similar Reads
Find the maximum path sum between two leaves of a binary tree using JavaScript
Given the root of a binary tree, return the maximum path sum of any non-empty path. A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to p
6 min read
Count the Number of Nodes in a Complete Binary tree using JavaScript
We need to count the number of the nodes in the complete binary tree using JavaScript. The complete binary tree is a binary tree in which every level then except possibly the last, is completely filled and all the nodes are as far left as possible. There are several approaches for counting the numbe
4 min read
Print the nodes having exactly one child in a Binary tree using JavaScript
Given a binary tree, our task is to return the number of nodes in the Binary tree that have at least one child otherwise return â-1â if no such node exists. Examples: Input: 1 / \ 2 3 / \ 4 5 / 6Output: 3Explanation:There are three nodes in the Binary tree that have at least one child that are 1,2,4
4 min read
Find the Preorder Successor of a Given Node in a Binary Tree using JavaScript
The Preorder successor of a given node is a node that occurs after the given node in the preorder traversal of the binary tree. The preorder traversal is a traversal in which the root node is visited first, then the left child, and then the right child. Example: The pre-order successor of a binary t
2 min read
Find the Sum of All Left Leaves in a Given Binary Tree using JavaScript
Given a Binary Tree, find the sum of all left leaves in it. A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. Finding the sum of all left leaves involves traversing the entire binary tree and checking each n
4 min read
Merge Two Balanced Binary Search Trees using JavaScript
We are given two different Balanced Binary Search Trees and we have to merge them to form a single balanced binary search tree. A Balanced Binary Search Tree (BST) is a binary search tree that keeps its height close to the minimum possible height. This is achieved by ensuring that the height differe
4 min read
Difference Between Sums of Odd Level and Even Level Nodes of a Binary Tree using JavaScript
Given a Binary Tree, our task is to find the difference between the sum of nodes at odd level and the sum of nodes at even level using JavaScript. Example: Input: 15 / \ 12 16 / \ \ 11 14 18 / / \ 13 17 19 Output: -19Explanation: In the above tree, sum of nodes at odd level is (15 + 11 + 14 + 18)whi
4 min read
Convert a Binary Tree to a Binary Search Tree using JavaScript
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that it keeps the original structure of the Binary Tree. Example: To demonstrate the conversion of the Binary Tree to the Binary Search Tree. Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10
2 min read
Boundary Traversal of Binary Tree using JavaScript
The Boundary Traversal of the Binary Tree can be done by traversing the left, right, and leaf parts of the Binary Tree. We will break the Boundary Traversal of Binary Tree using JavaScript in three parts. First, we will traverse the left part, right part, and leaf parts of the Binary Tree and print
4 min read
Check Symmetrical Binary Tree using JavaScript
Given a binary tree, our task is to check whether it is Symmetrical Binary tree. In other words, we need to check whether the binary tree is a mirror of itself. Example: Input: 11 / \ 12 12 / \ / \ 13 14 14 13Output: True Input: 11 / \ 12 12 \ \ 13 13Output: FalseBelow are the approaches to check Sy
3 min read