Distance between two nodes of binary tree with node values from 1 to N | Java program to find minimum distance between two nodes in binary tree ; Function to get minimum path distance ; count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Driver program
import java . util . * ; class GFG { static int minDistance ( int n1 , int 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 ; 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 ; int result = bitCount1 + bitCount2 - 2 * disSimilarBitPosition ; return result ; } public static void main ( String args [ ] ) { int n1 = 12 , n2 = 5 ; System . out . println ( minDistance ( n1 , n2 ) ) ; } }