0270. Closest Binary Search Tree Value
Last updated
Last updated
**Input:** root = [4,2,5,1,3], target = 3.714286
**Output:** 4**Input:** root = [1], target = 4.428571
**Output:** 1/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
while (root != null) {
res = Math.abs(target - res) < Math.abs(target - root.val) ? res : root.val;
if (target == root.val) {
break;
} else if (target < root.val) {
root = root.left;
} else {
root = root.right;
}
}
return res;
}
}