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 Code
< ? php function minDistance ( $ n1 , $ n2 ) { $ bitCount1 = floor ( log ( $ n1 , 2 ) ) + 1 ; $ bitCount2 = floor ( log ( $ n2 , 2 ) ) + 1 ; $ 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 ; $ result = $ bitCount1 + $ bitCount2 - 2 * $ disSimilarBitPosition ; return $ result ; } $ n1 = 12 ; $ n2 = 5 ; echo minDistance ( $ n1 , $ n2 ) ; ? >