Find a number in minimum steps | Python program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; q . pop ( ) To avoid infinite loop ; Check if dequeued number is same as n ; Insert children of dequeued node to queue ; Driver code
from collections import deque NEW_LINE InF = 99999 NEW_LINE class number : NEW_LINE INDENT def __init__ ( self , n , l ) : NEW_LINE INDENT self . no = n NEW_LINE self . level = l NEW_LINE DEDENT DEDENT def findnthnumber ( n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE r = number ( 0 , 1 ) NEW_LINE q . append ( r ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE if ( temp . no >= InF or temp . no <= - InF ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( temp . no == n ) : NEW_LINE INDENT print ( " Found ▁ number ▁ n ▁ at ▁ level " , temp . level - 1 ) NEW_LINE break NEW_LINE DEDENT q . append ( number ( temp . no + temp . level , temp . level + 1 ) ) NEW_LINE q . append ( number ( temp . no - temp . level , temp . level + 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT findnthnumber ( 13 ) NEW_LINE DEDENT