Distance between two nodes of binary tree with node values from 1 to N | C # 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 code
using System ; 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 ; Console . WriteLine ( minDistance ( n1 , n2 ) ) ; } }