class Solution(object): def closestKValues(self, root, target, k): """ :type root: TreeNode :type target: float :type k: int :rtype: List[int] """ def dfs(root, target, heap): if root is None: return dfs(root.left, target, heap) heapq.heappush(heap, (abs(root.val - target), root.val)) dfs(root.right, target, heap) heap =  dfs(root, target, heap) output =  for _ in range(k): output.append(heapq.heappop(heap)) return output
Cool, but this takes
O(NlogN) time. You can do it in
O(k + (N - k)*log(k)). Check out https://leetcode.com/discuss/110964/python-solution-o-n-klog-k-time
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.