---
description: LeetCode 272
---

# Closest Binary Search Tree Value II

```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from queue import PriorityQueue
class Solution:
    def closestKValues(self, root, target, k):
        """
        :type root: TreeNode
        :type target: float
        :type k: int
        :rtype: List[int]
        """
        self.pq = PriorityQueue()
        self.dfs(root, target, k)
        count = 0
        res = []
        while not self.pq.empty() and count < k:
            item = self.pq.get()[1]
            res.append(item)
            count += 1
        return res  
    
    def dfs(self, root, target, k):
        
        if root:
            self.pq.put((abs(target-root.val), root.val))
            self.dfs(root.left, target, k)
            self.dfs(root.right, target, k)
```
