272 Closest Binary Search Tree Value II
from queue import PriorityQueue
class Solution:
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
fix_same_dist_conflict = [0]
pq = PriorityQueue()
def pre_order_dfs(root):
if root:
# if the current distance exceeds the current
# smallest maximum of the pq (inverse logic)
cur_dist = -abs(target - root.val)
if pq.qsize() == k and pq.queue[0][0] < cur_dist:
pq.get()
pq.put((cur_dist, fix_same_dist_conflict[0], root))
elif pq.qsize() < k:
pq.put((cur_dist, fix_same_dist_conflict[0], root))
fix_same_dist_conflict[0] += 1
pre_order_dfs(root.left)
pre_order_dfs(root.right)
pre_order_dfs(root)
solution = []
while not pq.empty():
solution.append(pq.get()[2].val)
return solutionLast updated