very easy python with heap


  • 0
    Z
    • def closestKValues(self, root, target, k):
        """
        :type root: TreeNode
        :type target: float
        :type k: int
        :rtype: List[int]
        """
        heap=[]
        def dfs(root):
            if root:
                heapq.heappush(heap,(-abs(root.val-target),root.val))
                dfs(root.right)
                dfs(root.left)
      
                if len(heap)>k:
                    heapq.heappop(heap) 
        dfs(root)
        
        return [i[1] for i in heap]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.