Open In App

Distance between two nodes of binary tree with node values from 1 to N

Last Updated : 25 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree with 1 as its root and for any parent i its left child will be 2*i and right child will be 2*i+1. The task is to find the minimum distance between two nodes n1 and n2.

           
               1
            /      \
           2        3
         /  \      / \
        4    5    6   7
      /  \  / \  / \ / \
     .  .  .  . .  .  .  . 

Examples

Input : n1 = 7, n2 = 10
Output : 5

Input : n1 = 6, n2 = 7
Output : 4

There are so many ways to find the minimum distance between two given nodes of a binary tree.
Here is an efficient way to find the same with the help of binary representation of given nodes. For any node, take a closer look on its binary representation. For example, consider node 9. Binary representation of 9 is 1001. So to find the path from root to a node, find the binary representation of that node and move from left to right in that binary representation and move to right child in tree if a 1 is encountered and move to left child if a 0 is encountered. 

Path of 9 as per bit representation
        1
       / \
      2   3
     /\   /\
    4  5 6  7
   /\ 
  8  9.

Hence, for finding the minimum distance between two nodes, we will try to find the common part of binary representation of both nodes which is actually the common path from root to LCA. Let first k-bits for both node is same. Also, if binary form is of n-bit then it shows that path distance from root to that node is of n length. Hence from above statements, we can easily conclude that: If m and n is the bit-length of two nodes and k-starting bits of both node’s value are same then the minimum distance between both node will be: m + n – 2*k.
Note: Last similar bit shows the position of LCA in given binary tree.

Below is the implementation of the above approach:

C++




// C++ program to find minimum distance between
// two nodes in binary tree
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to get minimum path distance
int minDistance(int n1, int n2)
{
    /** find the 1st dis-similar bit **/
    // count bit length of n1 and n2
    int bitCount1 = floor(log2(n1)) + 1;
    int bitCount2 = floor(log2(n2)) + 1;
 
    // find bit difference and maxBit
    int bitDiff = abs(bitCount1 - bitCount2);
    int maxBitCount = max(bitCount1, bitCount2);
 
    if (bitCount1 > bitCount2) {
        n2 = n2 * pow(2, bitDiff);
    }
    else {
        n1 = n1 * pow(2, bitDiff);
    }
 
    int xorValue = n1 ^ n2;
    int bitCountXorValue;
   
      if( xorValue == 0)
      bitCountXorValue = 1;
    else
    {
       bitCountXorValue = floor(log2(xorValue)) + 1;
    }
    int disSimilarBitPosition = maxBitCount -
                                     bitCountXorValue;
   
    // calculate result by formula
    int result = bitCount1 + bitCount2 -
                         2 * disSimilarBitPosition;
    return result;
}
 
// Driver program
int main()
{
    int n1 = 12, n2 = 5;
 
    cout << minDistance(n1, n2);
 
    return 0;
}


Java




// Java program to find minimum distance between
// two nodes in binary tree
import java.util.*;
 
class GFG
{
    // Function to get minimum path distance
    static int minDistance(int n1, int n2)
    {
        /** find the 1st dis-similar bit **/
        // count bit length of n1 and n2
     
        int bitCount1 =(int) Math.floor((Math.log(n1) /
                        Math.log(2))) + 1;
        int bitCount2 = (int)Math.floor((Math.log(n2) /
                        Math.log(2))) + 1;
 
        // find bit difference and maxBit
        int bitDiff = Math.abs(bitCount1 - bitCount2);
        int maxBitCount = Math.max(bitCount1, bitCount2);
 
        if (bitCount1 > bitCount2)
        {
            n2 = n2 *(int) Math.pow(2, bitDiff);
        }
        else   
        {
            n1 = n1 *(int) Math.pow(2, bitDiff);
        }
       
       
        int xorValue = n1 ^ n2;
        int bitCountXorValue;
       
        if( xorValue == 0)
          bitCountXorValue = 1;
        else
        {
           bitCountXorValue = (int)Math.floor((Math.log(xorValue) /
                                Math.log(2))) + 1;
        }
        int disSimilarBitPosition = maxBitCount -
                                         bitCountXorValue;
        
 
        // calculate result by formula
        int result = bitCount1 + bitCount2 - 2 * disSimilarBitPosition;
        return result;
    }
 
    // Driver program
    public static void main(String args[])
    {
        int n1 = 12, n2 = 5;
        System.out.println(minDistance(n1, n2));
    }
}
 
// This code is contributed by
// Sanjit_Prasad


Python3




# Python 3 program to find minimum distance
# between two nodes in binary tree
from math import log2
 
# Function to get minimum path distance
def minDistance(n1, n2):
     
    # find the 1st dis-similar bit
    # count bit length of n1 and n2
    bitCount1 = int(log2(n1)) + 1
    bitCount2 = int(log2(n2)) + 1
 
    # find bit difference and maxBit
    bitDiff = abs(bitCount1 - bitCount2)
    maxBitCount = max(bitCount1, bitCount2)
 
    if (bitCount1 > bitCount2):
        n2 = int(n2 * pow(2, bitDiff))
     
    else:
        n1 = int(n1 * pow(2, bitDiff))
 
    xorValue = n1 ^ n2
    if xorValue == 0:
        bitCountXorValue = 1
    else:
        bitCountXorValue = int(log2(xorValue)) + 1
    disSimilarBitPosition = (maxBitCount -
                             bitCountXorValue)
 
    # calculate result by formula
    result = (bitCount1 + bitCount2 - 2 *
                   disSimilarBitPosition)
    return result
 
# Driver Code
if __name__ == '__main__':
    n1 = 12
    n2 = 5
 
    print(minDistance(n1, n2))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to find minimum distance between
// two nodes in binary tree
using System;
     
class GFG
{
    // Function to get minimum path distance
    static int minDistance(int n1, int n2)
    {
        /** find the 1st dis-similar bit **/
        // count bit length of n1 and n2
     
        int bitCount1 =(int) Math.Floor((Math.Log(n1) /
                        Math.Log(2))) + 1;
        int bitCount2 = (int)Math.Floor((Math.Log(n2) /
                        Math.Log(2))) + 1;
 
        // find bit difference and maxBit
        int bitDiff = Math.Abs(bitCount1 - bitCount2);
        int maxBitCount = Math.Max(bitCount1, bitCount2);
 
        if (bitCount1 > bitCount2)
        {
            n2 = n2 *(int) Math.Pow(2, bitDiff);
        }
        else
        {
            n1 = n1 *(int) Math.Pow(2, bitDiff);
        }
 
        int xorValue = n1 ^ n2;
        
       
        int bitCountXorValue;
       
        if( xorValue == 0)
          bitCountXorValue = 1;
        else
        {
           bitCountXorValue = (int)Math.Floor((Math.Log(xorValue) /
                                Math.Log(2))) + 1;
        }
         
        int disSimilarBitPosition = maxBitCount - bitCountXorValue;
 
        // calculate result by formula
        int result = bitCount1 + bitCount2 - 2 * disSimilarBitPosition;
        return result;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int n1 = 12, n2 = 5;
        Console.WriteLine(minDistance(n1, n2));
    }
}
 
/* This code contributed by PrinciRaj1992 */


PHP




<?php
// PHP program to find minimum distance
// between two nodes in binary tree
 
// Function to get minimum path distance
function minDistance($n1, $n2)
{
    /** find the 1st dis-similar bit **/
    // count bit length of n1 and n2
    $bitCount1 = floor(log($n1, 2)) + 1;
    $bitCount2 = floor(log($n2, 2)) + 1;
 
    // find bit difference and maxBit
    $bitDiff = abs($bitCount1 - $bitCount2);
    $maxBitCount = max($bitCount1, $bitCount2);
 
    if ($bitCount1 > $bitCount2)
    {
        $n2 = $n2 * pow(2, $bitDiff);
    }
    else
    {
        $n1 = $n1 * pow(2, $bitDiff);
    }
 
    $xorValue = $n1 ^ $n2;
    $bitCountXorValue = floor(log($xorValue, 2)) + 1;
    $disSimilarBitPosition = $maxBitCount -
                             $bitCountXorValue;
 
    // calculate result by formula
    $result = $bitCount1 + $bitCount2 - 2 *
              $disSimilarBitPosition;
    return $result;
}
 
// Driver Code
$n1 = 12;
$n2 = 5;
 
echo minDistance($n1, $n2);
 
// This code is contributed by akt_mit
?>


Javascript




<script>
 
 
// Javascript program to find minimum distance between
// two nodes in binary tree
 
// Function to get minimum path distance
function minDistance(n1, n2)
{
    /** find the 1st dis-similar bit **/
    // count bit length of n1 and n2
    var bitCount1 = Math.floor(Math.log2(n1)) + 1;
    var bitCount2 = Math.floor(Math.log2(n2)) + 1;
 
    // find bit difference and maxBit
    var bitDiff = Math.abs(bitCount1 - bitCount2);
    var maxBitCount = Math.max(bitCount1, bitCount2);
 
    if (bitCount1 > bitCount2) {
        n2 = n2 * Math.pow(2, bitDiff);
    }
    else {
        n1 = n1 * Math.pow(2, bitDiff);
    }
 
    var xorValue = n1 ^ n2;
    var bitCountXorValue;
   
      if( xorValue == 0)
      bitCountXorValue = 1;
    else
    {
       bitCountXorValue = Math.floor(Math.log2(xorValue)) + 1;
    }
    var disSimilarBitPosition = maxBitCount -
                                     bitCountXorValue;
   
    // calculate result by formula
    var result = bitCount1 + bitCount2 -
                         2 * disSimilarBitPosition;
    return result;
}
 
// Driver program
var n1 = 12, n2 = 5;
document.write( minDistance(n1, n2));
 
</script>


Output

5

Time Complexity: O(1)
Auxiliary Space: O(1)



Similar Reads

Check if all the Nodes in a Binary Tree having common values are at least D distance apart
Given a Binary Tree and an integer D, the task is to check if the distance between all pairs of the same node values in the Tree is? D or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: D = 7 1 / \ 2 3 / \ / \ 4 3 4 4 Output: Yes Explanation: The repeated value of nodes are 3 and 4. The distance between the two nodes
11 min read
Queries to find distance between two nodes of a Binary tree
Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from other. We have already discussed a method which uses segment tree to reduce the query time to O(logn), here the task is to reduce
22 min read
Find distance between two nodes in the given Binary tree for Q queries
Given a binary tree having N nodes and weight of N-1 edges. The distance between two nodes is the sum of the weight of edges on the path between two nodes. Each query contains two integers U and V, the task is to find the distance between nodes U and V. Examples: Input: Output: 3 5 12 12 Explanation: Distance between nodes 1 to 3 = weight(1, 3) = 2
16 min read
Queries to find distance between two nodes of a Binary tree - O(logn) method
Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other. This problem has been already discussed in previous post but it uses three traversals of the Binary tree, one for finding Lowes
23 min read
Shortest distance between two nodes in an infinite binary tree
Consider you have an infinitely long binary tree having a pattern as below: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Given two nodes with values x and y. The task is to find the length of the shortest path between the two nodes. Examples: Input: x = 2, y = 3 Output: 2 Input: x = 4, y = 6 Output: 4Recommended PracticeShortest distan
15 min read
Find distance between two nodes of a Binary Tree
AucFind the distance between two keys in a binary tree, 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. Recommended PracticeMin distance between two given nodes of a Binary TreeTry It! The distance between two nodes can be obtained in terms of lowest common
34 min read
Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree
Given an N-ary tree root, the task is to find the number of non-leaf nodes in the tree such that all the leaf nodes in the subtree of the current node are at an equal distance from the current node. Example: Input: Tree in the below imageOutput: 4Explanation: The nodes {10, 3, 2, 4} have the distance between them and all the leaf nodes in their sub
11 min read
Distance of each node of a Binary Tree from the root node using BFS
Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to node 2 is 1. The distance from the root to node 3 i
9 min read
Sum of all nodes with smaller values at a distance K from a given node in a BST
Given a Binary Search Tree, a target node in the BST, and an integer value K, the task is to find the sum of all nodes that are at a distance K from the target node whose value is less than the target node. Examples: Input: target = 7, K = 2 Output: 11Explanation:The nodes at a distance K(= 2) from the node 7 is 1, 4, and 6. Therefore, the sum of n
26 min read
Minimum distance between two given nodes in an N-ary tree
Given a N ary Tree consisting of N nodes, the task is to find the minimum distance from node A to node B of the tree. Examples: Input: 1 / \ 2 3 / \ / \ \4 5 6 7 8A = 4, B = 3Output: 3Explanation: The path 4-&gt;2-&gt;1-&gt;3 gives the minimum distance from A to B. Input: 1 / \ 2 3 / \ \ 6 7 8A = 6, B = 7Output: 2 Approach: This problem can be solv
11 min read
Article Tags :
Practice Tags :