⚡Flashcard Drill➔
NeetCode #398LC-270EasyTreesNC Algo100
← Back to All Problems

#398 · #270 · Closest Binary Search Tree Value(最接近的二叉搜索树值)

📌 Problem Statement & Constraints

Given the root of a binary search tree and a floating-point target, return the value in the tree closest to the target. If several values are equally close, return the smallest. Constraints: the number of nodes is in [1, 10^4], 0 <= Node.val <= 10^9, 0 <= target <= 10^9.

💡 Core Algorithmic Approaches

  1. Descend the BST guided by target, keeping the closest value seen so far.
  2. At each node, update the best if the current value is closer, or equally close but smaller.
  3. Then move left when target < node.val and right otherwise.
  4. This is O(h) instead of the O(n) full traversal, because the BST ordering bounds where the closest value can be.

💻 Benchmark Python3 Implementation

class Solution:
    def closestValue(self, root: Optional[TreeNode], target: float) -> int:
        best = root.val
        cur = root
        while cur:
            d_cur = abs(cur.val - target)
            d_best = abs(best - target)
            # strictly closer, or equally close but smaller
            if d_cur < d_best or (d_cur == d_best and cur.val < best):
                best = cur.val
            if target < cur.val:
                cur = cur.left             # values only get smaller
            else:
                cur = cur.right
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(h): one root-to-leaf descent.
💾 Space Complexity
O(1) for the iterative version.

⚠️ Interview Pitfalls & Follow-ups

  • Traversing the whole tree: O(n) and unnecessary -- the BST ordering prunes the search.
  • Comparing with <= instead of the explicit tie-break: <= would keep the larger value on a tie, contradicting the requirement.
  • Assuming the answer is unique: the statement allows ties, so the smallest must be selected.
  • Stopping the descent after finding a close value: the closest value may be deeper along the path.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

最接近的二叉搜索树值

给你二叉搜索树的根节点 root 和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。如果有多个答案,返回最小的那个。约束:树中节点的数目在范围 [1, 10^4] 内;0 ≤ Node.val ≤ 10^9;-10^9 ≤ target ≤ 10^9。

核心要点

  • 利用 BST 有序性二分查找(标准解) :从根出发,比较 cur.val 与 target:若 cur.val &lt; target 则向右走,否则向左走;每步更新最优值。
  • 为什么这样能覆盖所有候选 :BST 中「最接近 target 的值」一定在从根到「target 应插入位置」的路径上,因为每步都能排除一半子树。
  • 并列时返回较小值 :比较时用严格小于 &lt; 更新最优值,这样并列时保留先遇到的(即较小的)。
  • 复杂度 :O(h) 时间、O(1) 空间。

常见陷阱

  • 用 &lt;= 更新最优值 :并列时会取到后遇到的(较大值),与题目「返回最小的」相反。
  • 遍历整棵树 :O(n),未利用 BST 的有序性。
  • 忘记处理 target == cur.val :会继续下行(虽然结果仍正确,但多做无用功)。
  • 递归实现但树退化成链 :递归深度 O(n) 可能栈溢出;迭代版本更安全。

参考实现

class Solution:
    def closestValue(self, root: 'TreeNode', target: float) -> int:
        best = root.val
        cur = root
        while cur:
            # 用严格小于,并列时保留先遇到的(较小值)
            if abs(cur.val - target) < abs(best - target):
                best = cur.val
            if target < cur.val:
                cur = cur.left
            elif target > cur.val:
                cur = cur.right
            else:
                break                   # 恰好相等,直接结束
        return best