Open In App

Find Distance Between Two Nodes of a Binary Tree using JavaScript

In computer science, binary trees are hierarchical data structures that consist of nodes. Each node can have­ two children at most - one on the le­ft side and one on the right. These­ structures have a top-to-bottom order. Solving for distance­ between any two give­n nodes is a problem often se­en 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:

Screenshot-2024-04-29-231412

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.

Example: To demonstrate finding the distance between two nodes of a Binary tree using brute force in 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.

Example: To demonsrtate finding the distance between two nodes of a Binary tree using JavaScript Lowest common ancestor.

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.

Example: To demonsrtate finding the distance between two nodes of Binary tree using single traversal in 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)

Article Tags :