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

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 = 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 = (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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to find minimum distance 
# between two nodes in binary tree
from math import floor, pow, 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 = floor(log2(n1)) + 1
    bitCount2 = floor(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
    bitCountXorValue = floor(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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 = (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 */

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


Output:

5


My Personal Notes arrow_drop_up

Discovering ways to develop a plane for soaring career goals

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.