272. Closest Binary Search Tree Value II
题干:
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
解释:
寻找BST中最接近目标的K个数字
思考:
首先BST中序遍历为有序,先转换成有序数列。 然后按照和target的绝对值的差排序,找到返回最前面的K个,时间复杂度是nlogn 如果使用一个最大堆,时间复杂度是nlogk 还有更好的办法,就是从两头开始删除,每次删除距离较大的那个。这样只要On就行了。
答案:
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
if not root: return []
stack = []
result = []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if len(result) < k: result.append(root.val)
elif abs(result[0] - target) > abs(root.val - target):
result.pop(0)
result.append(root.val)
else: break
root = root.right
return result