Find distance from root to given node in a binary tree | A class to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findDistance ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT dist = - 1 NEW_LINE if ( root . data == x ) : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dist = findDistance ( root . left , x ) NEW_LINE if dist >= 0 : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dist = findDistance ( root . right , x ) NEW_LINE if dist >= 0 : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT DEDENT DEDENT return dist NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . left = newNode ( 10 ) NEW_LINE root . right = newNode ( 15 ) NEW_LINE root . left . left = newNode ( 20 ) NEW_LINE root . left . right = newNode ( 25 ) NEW_LINE root . left . right . right = newNode ( 45 ) NEW_LINE root . right . left = newNode ( 30 ) NEW_LINE root . right . right = newNode ( 35 ) NEW_LINE print ( findDistance ( root , 45 ) ) NEW_LINE DEDENT