270. Closest Binary Search Tree Value

tree dfs

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

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. 初始化修正

    • res 初始化为根节点值,min_diff 初始化为根节点与 target 的差值,避免 inf 导致的逻辑错误。

  2. 差值比较逻辑

    • 直接比较当前节点与 target 的差值,动态更新 resmin_diff

  3. 剪枝优化

    • 根据二叉搜索树(BST)的性质,如果 target < node.val,只需搜索左子树;反之搜索右子树。这可以将时间复杂度从 O(n) 优化到平均 O(log n)。

  4. 处理相等差值

    • 如果多个节点与 target 的差值相同,选择值较小的节点(符合题目要求)。

dfs

iterative

Last updated

Was this helpful?