Check if all the Nodes in a Binary Tree having common values are at least D distance apart | Function to create a new node ; Function to count the frequency of node value present in the tree ; Function that returns the max distance between the nodes that have the same key ; If right and left subtree did not have node whose key is value ; Check if the current node is equal to value ; If the left subtree has no node whose key is equal to value ; If the right subtree has no node whose key is equal to value ; Function that finds if the distance between any same nodes is at most K ; Create the mp to look for same value of nodes ; Counting the frequency of nodes ; If the returned value of distance is exceeds dist ; Print the result ; Driver Code
mp = { } NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def frequencyCounts ( root ) : NEW_LINE INDENT global mp NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT mp [ root . key ] = mp . get ( root . key , 0 ) + 1 NEW_LINE frequencyCounts ( root . left ) NEW_LINE frequencyCounts ( root . right ) NEW_LINE DEDENT def computeDistance ( root , value ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT left = computeDistance ( root . left , value ) NEW_LINE right = computeDistance ( root . right , value ) NEW_LINE if ( left == - 1 and right == - 1 ) : NEW_LINE INDENT if ( root . key == value ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if ( left == - 1 ) : NEW_LINE INDENT return right + 1 NEW_LINE DEDENT if ( right == - 1 ) : NEW_LINE INDENT return left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + max ( left , right ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def solve ( root , dist ) : NEW_LINE INDENT global mp NEW_LINE frequencyCounts ( root ) NEW_LINE flag = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT if ( value > 1 ) : NEW_LINE INDENT result = computeDistance ( root , key ) NEW_LINE if ( result > dist or result == - 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if flag == 0 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE dist = 7 NEW_LINE solve ( root , dist ) NEW_LINE DEDENT