我们可以利用二分搜索树的特点 (左<根<右) 来快速定位,由于根节点是中间值,在往下遍历时,根据目标值和根节点的值大小关系来比较。如果节点值大于目标值,则应该找更小的值,于是到左子树去找,反之去右子树找。代码如下:
Solution 1 (Recursive)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
return inOrder(root, target, res);
}
private int inOrder(TreeNode root, double target, int res){
// base case
if(root == null){
return res;
}else if(root.val == target){
return root.val;
}
// recursive rule
if(Math.abs(root.val - target) < Math.abs(res - target)){
res = root.val;
}
if(root.val > target){
res = inOrder(root.left, target, res);
}else{
res = inOrder(root.right, target, res);
}
return res;
}
}
Solution 2 (Iterative)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
TreeNode curr = root;
while(curr != null){
if(Math.abs(curr.val - target) < Math.abs(res - target)){
res = curr.val;
}
curr = curr.val > target ? curr.left : curr.right;
}
return res;
}
}