Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
- Given target value is a floating point.
- You are guaranteed to have only one unique value in the BST that is closest to the target.
方法:递归查找。如果当前节点值小于目标值,则结果只可能是当前节点值或者右子树中的值;如果当前节点值大于目标值,则结果只可能是当前节点值或者左子树中的值。
public class Solution {
private int value;
private void find(TreeNode root, double target) {
if (Math.abs(root.val-target) < Math.abs(value-target)) value = root.val;
if (root.val < target && root.right != null) find(root.right, target);
if (root.val > target && root.left != null) find(root.left, target);
}
public int closestValue(TreeNode root, double target) {
value = root.val;
find(root, target);
return value;
}
}
本文介绍了一种递归方法,在给定的非空二叉搜索树中找到最接近指定目标值的节点值。该方法通过比较当前节点值与目标值之间的差异来决定搜索方向,确保了高效地找到最接近的目标值。
939

被折叠的 条评论
为什么被折叠?



