270. Closest Binary Search Tree Value
tree dfs
Last updated
Was this helpful?
tree dfs
Last updated
Was this helpful?
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:
Example 2:
Constraints:
The number of nodes in the tree is in the range [1, 10
4
]
.
0 <= Node.val <= 10
9
-10
9
<= target <= 10
9
分析
初始化修正:
res
初始化为根节点值,min_diff
初始化为根节点与 target
的差值,避免 inf
导致的逻辑错误。
差值比较逻辑:
直接比较当前节点与 target
的差值,动态更新 res
和 min_diff
。
剪枝优化:
根据二叉搜索树(BST)的性质,如果 target < node.val
,只需搜索左子树;反之搜索右子树。这可以将时间复杂度从 O(n) 优化到平均 O(log n)。
处理相等差值:
如果多个节点与 target
的差值相同,选择值较小的节点(符合题目要求)。
dfs
iterative