Find Distance Between Two Nodes of a Binary Tree using JavaScript
Last Updated :
30 Apr, 2024
In computer science, binary trees are hierarchical data structures that consist of nodes. Each node can have two children at most - one on the left side and one on the right. These structures have a top-to-bottom order. Solving for distance between any two given nodes is a problem often seen with binary trees. We'll look at different ways to find this distance in JavaScript.
Problem Description: Given a binary tree and two node values, the task is to find the distance between the two nodes.
Consider the following binary tree:

Explanation: To find the distance between nodes 4 and 6, we first locate their common ancestor, which is node 2. From this ancestor, the path to node 4 is of length 1, and the path to node 6 is of length 3. Therefore, the total distance between nodes 4 and 6 is 4.
Output: The distance between nodes 4 and 6 in the binary tree is 4.
There are several approaches to find the distance between two nodes of a Binary tree using JavaScript which are as follows:
Using Brute Force
In the brute force approach, we traverse the binary tree recursively, calculating the distance from the root to both target nodes. We then sum up these distances to find the total distance between the nodes.
- In this approach, for each node in the binary tree, we find the distance to both target nodes.
- We start from the root and traverse the tree recursively.
- We calculate the distance to both target nodes for each node encountered using depth-first search.
- Finally, we sum up the distances from the root to both nodes to get the total distance.
Example: To demonstrate finding the distance between two nodes of a Binary tree using brute force in JavaScript.
JavaScript
class BinaryNode {
constructor(val)
{
this.val = val;
this.left = null;
this.right = null;
}
}
// Function to find distance between
// two nodes using brute force approach
function findDistanceBruteForce(root, p, q)
{
// Function to find distance
// from root to a given node
function findDepth(node, target)
{
if (!node) return 0;
if (node.val === target) return 0;
const left = findDepth(node.left, target);
const right = findDepth(node.right, target);
if (left !== -1) return left + 1;
if (right !== -1) return right + 1;
return -1;
}
const distanceP = findDepth(root, p);
const distanceQ = findDepth(root, q);
return distanceP + distanceQ;
}
// Construct the binary tree
const root = new BinaryNode(1);
root.left = new BinaryNode(2);
root.right = new BinaryNode(3);
root.left.left = new BinaryNode(4);
root.left.right = new BinaryNode(5);
root.right.right = new BinaryNode(6);
const node1 = 4;
const node2 = 6;
// Find distance between node1 and node2 using brute force approach
console.log("Distance between", node1,
"and", node2, "using brute force approach is",
findDistanceBruteForce(root, node1, node2));
Output:
Distance between 4 and 6 using brute force approach is 4
Time Complexity: O(n^2)
Space Complexity: O(h)
Using Lowest Common Ancestor (LCA)
To optimize the brute force approach, we utilize the concept of the Lowest Common Ancestor (LCA). We first find the LCA of the two target nodes, then calculate the distances from the LCA to both nodes, and finally sum up these distances to get the total distance between the nodes.
- We can optimize the previous approach by first finding the Lowest Common Ancestor (LCA) of the two target nodes.
- Once we have the LCA, we can calculate the distances from the LCA to both target nodes using depth-first search.
- Finally, we sum up these distances to get the total distance between the target nodes.
Example: To demonsrtate finding the distance between two nodes of a Binary tree using JavaScript Lowest common ancestor.
JavaScript
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));
Output:
Distance between 4 and 6 using optimized approach with LCA is 4
Time Complexity: O(n)
Space Complexity: O(h)
Using Single Traversal
In this approach, we further optimize by finding both the LCA and the distances from the LCA to both nodes in a single traversal of the binary tree. This reduces the time complexity compared to the previous approaches.
- We can further optimize by finding both the LCA and the distances from the LCA to both nodes in a single traversal of the binary tree.
- During the traversal, if we find both target nodes, we return their depths to their common ancestor.
- If only one node is found, we return its depth and continue the traversal.
- Once both nodes are found, we return their depths to their common ancestor and calculate the total distance.
Example: To demonsrtate finding the distance between two nodes of Binary tree using single traversal in JavaScript.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Function to find the distance
// between two nodes in a binary tree
function findDistance(root, p, q) {
// Helper function to find the
// distance from a node to the target
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;
}
// Helper function to find the Lowest
// Common Ancestor (LCA) of two nodes
function findLCA(node, p, q) {
if (!node || node.val === p || node.val === q) return node;
const left = findLCA(node.left, p, q);
const right = findLCA(node.right, p, q);
if (left && right) return node;
return left ? left : right;
}
// Find the Lowest Common
// Ancestor (LCA) of the two nodes
const lca = findLCA(root, p, q);
// Calculate the distance
// from the LCA to each node
const distanceP = findDepth(lca, p, 0);
const distanceQ = findDepth(lca, q, 0);
// Total distance between the nodes
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
console.log("Distance between", node1,
"and", node2,
"using further optimized approach with single traversal is",
findDistance(root, node1, node2));
Output:
Distance between 4 and 6 using further optimized approach with single traversal is 4
Time Complexity: O(n)
Space Complexity: O(h)
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. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
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
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
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
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
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 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
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
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