```
public int closestValue(TreeNode root, double target) {
TreeNode result = root;
while(root != null) {
if(root.val == target) return root.val;
result = Math.abs(root.val - target) < Math.abs(result.val - target) ? root : result;
root = root.val > target ? root.left : root.right;
}
return result.val;
}
```