#NEWLINE# def closestKValues( self , root , target , k ) : #NEWLINE# #INDENT# '\n        :type root: TreeNode\n        :type target: float\n        :type k: int\n        :rtype: List[int]\n        ' #NEWLINE# def nextNode( stack , child1 , child2 ) : #NEWLINE# #INDENT# if stack : #NEWLINE# #INDENT# if child2 ( stack ) : #NEWLINE# #INDENT# stack . append ( child2 ( stack ) ) #NEWLINE# while child1 ( stack ) : #NEWLINE# #INDENT# stack . append ( child1 ( stack ) ) #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# child = stack . pop ( ) #NEWLINE# while ( stack and ( child is child2 ( stack ) ) ) : #NEWLINE# #INDENT# child = stack . pop ( ) #NEWLINE# #UNINDENT# #UNINDENT# #UNINDENT# #UNINDENT# backward = ( lambda stack : stack [ ( - 1 ) ] . left ) #NEWLINE# forward = ( lambda stack : stack [ ( - 1 ) ] . right ) #NEWLINE# stack = [ ] #NEWLINE# while root : #NEWLINE# #INDENT# stack . append ( root ) #NEWLINE# root = ( root . left if ( target < root . val ) else root . right ) #NEWLINE# #UNINDENT# dist = ( lambda node : abs ( ( node . val - target ) ) ) #NEWLINE# forward_stack = stack [ : ( stack . index ( min ( stack , key = dist ) ) + 1 ) ] #NEWLINE# backward_stack = list ( forward_stack ) #NEWLINE# nextNode ( backward_stack , backward , forward ) #NEWLINE# result = [ ] #NEWLINE# for _ in xrange ( k ) : #NEWLINE# #INDENT# if ( forward_stack and ( ( not backward_stack ) or ( dist ( forward_stack [ ( - 1 ) ] ) < dist ( backward_stack [ ( - 1 ) ] ) ) ) ) : #NEWLINE# #INDENT# result . append ( forward_stack [ ( - 1 ) ] . val ) #NEWLINE# nextNode ( forward_stack , forward , backward ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( backward_stack and ( ( not forward_stack ) or ( dist ( backward_stack [ ( - 1 ) ] ) <= dist ( forward_stack [ ( - 1 ) ] ) ) ) ) : #NEWLINE# #INDENT# result . append ( backward_stack [ ( - 1 ) ] . val ) #NEWLINE# nextNode ( backward_stack , backward , forward ) #NEWLINE# #UNINDENT# #UNINDENT# #UNINDENT# return result