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++
// C++ program to find minimum distance between// two nodes in binary treeÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to get minimum path distanceint 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 programint main(){Â Â Â Â int n1 = 12, n2 = 5;Â
    cout << minDistance(n1, n2);Â
    return 0;} |
Java
// Java program to find minimum distance between// two nodes in binary treeimport 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 treefrom math import log2Â
# Function to get minimum path distancedef 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 Codeif __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 treeusing 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 distancefunction 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 programvar n1 = 12, n2 = 5;document.write( minDistance(n1, n2));Â
</script> |
5
Time Complexity: O(1)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



