Get level of a node in binary tree | iterative approach | Python3 program to find closest value in Binary search Tree ; Helper function that allocates a new node with the given data and None left and right poers . ; utility function to return level of given node ; extra None is appended to keep track of all the nodes to be appended before level is incremented by 1 ; Driver Code ; create a binary tree ; return level of node
_MIN = - 2147483648 NEW_LINE _MAX = 2147483648 NEW_LINE class getnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getlevel ( root , data ) : NEW_LINE INDENT q = [ ] NEW_LINE level = 1 NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( temp == None ) : NEW_LINE INDENT if len ( q ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( q [ 0 ] != None ) : NEW_LINE INDENT q . append ( None ) NEW_LINE DEDENT level += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( temp . data == data ) : NEW_LINE INDENT return level NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getnode ( 20 ) NEW_LINE root . left = getnode ( 10 ) NEW_LINE root . right = getnode ( 30 ) NEW_LINE root . left . left = getnode ( 5 ) NEW_LINE root . left . right = getnode ( 15 ) NEW_LINE root . left . right . left = getnode ( 12 ) NEW_LINE root . right . left = getnode ( 25 ) NEW_LINE root . right . right = getnode ( 40 ) NEW_LINE level = getlevel ( root , 30 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 30 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 30 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 12 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 12 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 12 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 25 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 25 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 25 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 27 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 27 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 27 ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT