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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read