LeetCode 0272. Closest Binary Search Tree Value II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0272. Closest Binary Search Tree Value II

Description

Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order.

You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

 

Example 1:

Input: root = [4,2,5,1,3], target = 3.714286, k = 2
Output: [4,3]

Example 2:

Input: root = [1], target = 0.000000, k = 1
Output: [1]

 

Constraints:

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104.
  • 0 <= Node.val <= 109
  • -109 <= target <= 109

 

Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?

Solutions

Solution 1

PythonJavaC++Go
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]: def dfs(root): if root is None: return dfs(root.left) if len(q) < k: q.append(root.val) else: if abs(root.val - target) >= abs(q[0] - target): return q.popleft() q.append(root.val) dfs(root.right) q = deque() dfs(root) return list(q)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !