Question:
Give a BST, find a node whose value is closest to the target.
// when calling this method, set minDiff = Integer.MAX_VALUE, prev = null;
public static Node closestValue(Node root, int target, int minDiff, Node prev) {
if (root == null) return prev;
int diffV = Math.abs(root.value - target);
if (diffV > minDiff) return prev;
prev = root;
minDiff = diffV;
if (root.value == target) {
return root;
} else if (root.value > target) {
return closestValue(root.left, target, minDiff, prev);
} else {
return closestValue(root.right, target, minDiff, prev);
}
}
本文介绍了一种在二叉搜索树(BST)中寻找最接近指定目标值节点的方法。通过递归遍历BST,该算法能够高效地找到与目标值最接近的节点。
968

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



