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

Last Updated : 25 Nov, 2022

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

 ` ``\$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

 ``

Output

`5`

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

Article Tags :
Practice Tags :