Distance between two nodes of binary tree with node values from 1 to N | Function to get minimum path distance ; count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Driver program
function minDistance ( n1 , n2 ) { var bitCount1 = Math . floor ( Math . log2 ( n1 ) ) + 1 ; var bitCount2 = Math . floor ( Math . log2 ( n2 ) ) + 1 ; 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 ; var result = bitCount1 + bitCount2 - 2 * disSimilarBitPosition ; return result ; } var n1 = 12 , n2 = 5 ; document . write ( minDistance ( n1 , n2 ) ) ;