great solution, and the way to init and get succ/pred has been added to my code lib. here is the python version:

```
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
ret = []
succ = []
pred = []
self.initializePredecessorStack(root, target, pred)
self.initializeSuccessorStack(root, target, succ)
if succ and pred and succ[-1].val == pred[-1].val:
self.getNextPredecessor(pred)
while k > 0:
if not succ:
ret.append(self.getNextPredecessor(pred))
elif not pred:
ret.append(self.getNextSuccessor(succ))
else:
succ_diff = abs(succ[-1].val - target)
pred_diff = abs(pred[-1].val - target)
if succ_diff < pred_diff :
ret.append(self.getNextSuccessor(succ));
else:
ret.append(self.getNextPredecessor(pred));
k -= 1
return ret
def initializeSuccessorStack(self, root, target, succ):
while root:
if root.val == target:
succ.append(root)
break
elif root.val > target:
succ.append(root)
root = root.left
else:
root = root.right
def initializePredecessorStack(self, root, target, pred):
while root:
if root.val == target:
pred.append(root)
break
elif root.val < target:
pred.append(root)
root = root.right
else:
root = root.left
def getNextSuccessor(self, succ):
curr = succ.pop()
ret = curr.val
curr = curr.right
while curr:
succ.append(curr)
curr = curr.left
return ret
def getNextPredecessor(self, pred):
curr = pred.pop()
ret = curr.val
curr = curr.left
while curr:
pred.append(curr)
curr = curr.right
return ret
```