Distance between two nodes of binary tree with node values from 1 to N | Python 3 program to find minimum distance between two nodes in binary tree ; Function to get minimum path distance ; find the 1 st dis - similar bit count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Driver Code
from math import log2 NEW_LINE def minDistance ( n1 , n2 ) : NEW_LINE INDENT bitCount1 = int ( log2 ( n1 ) ) + 1 NEW_LINE bitCount2 = int ( log2 ( n2 ) ) + 1 NEW_LINE bitDiff = abs ( bitCount1 - bitCount2 ) NEW_LINE maxBitCount = max ( bitCount1 , bitCount2 ) NEW_LINE if ( bitCount1 > bitCount2 ) : NEW_LINE INDENT n2 = int ( n2 * pow ( 2 , bitDiff ) ) NEW_LINE DEDENT else : NEW_LINE INDENT n1 = int ( n1 * pow ( 2 , bitDiff ) ) NEW_LINE DEDENT xorValue = n1 ^ n2 NEW_LINE if xorValue == 0 : NEW_LINE INDENT bitCountXorValue = 1 NEW_LINE DEDENT else : NEW_LINE INDENT bitCountXorValue = int ( log2 ( xorValue ) ) + 1 NEW_LINE DEDENT disSimilarBitPosition = ( maxBitCount - bitCountXorValue ) NEW_LINE result = ( bitCount1 + bitCount2 - 2 * disSimilarBitPosition ) NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 12 NEW_LINE n2 = 5 NEW_LINE print ( minDistance ( n1 , n2 ) ) NEW_LINE DEDENT