Given the root
of a binary search tree and a target
value, return the value in the BST that is closest to the target
.
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286 Output: 4
Example 2:
Input: root = [1], target = 4.428571 Output: 1
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. 0 <= Node.val <= 109
-109 <= target <= 109
在二叉搜索树里查找一个数,如果不用二分查找法那就对不起二叉搜索树的名字。我们知道二叉搜索树的左子树的所有节点值都比根节点值小,右子树所有节点值都比根节点值大,因此很容易从根节点把树划分成两棵子树,通过判断可以排除掉一棵子树即减少一半的查找空间。
本题要求从一棵二叉搜索树找到一个最靠近目标数的节点(即差值绝对值最小)。要用二分查找法的关键点是如何判断该排除左子树还是右子树。
1)如果目标数等于根节点值,差值绝对值为0就是最靠近的节点,直接返回。
2)如果目标数小于根节点值,由于右子树上所有节点值都比根节点值大,因此它们都不可能比根节点更靠近目标数,因此可以排除右子树,继续查找左子树。
2)如果目标数大于根节点值,由于左子树上所有节点值都比根节点值小,因此它们都不可能比根节点更靠近目标数。因此可以排除左子树,继续查找右子树。
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
res = root.val
while root:
if target == root.val:
return root.val
res = res if abs(root.val - target) > abs(res - target) else root.val
if target < root.val:
root = root.left
else:
root = root.right
return res