---
# System prepended metadata

title: 0270. Closest Binary Search Tree Value
tags: [Leetcode, FaceBook, DFS, Easy]

---

# 0270. Closest Binary Search Tree Value
###### tags: `Leetcode` `Easy` `FaceBook` `DFS`
Link: https://leetcode.com/problems/closest-binary-search-tree-value/

## Code
```java=
class Solution {
    public int closestValue(TreeNode root, double target) {
        int result;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        double diff = root.val-target;
        while(!stack.isEmpty()){
            root = stack.pop();
            if(Math.abs(root.val-target)<Math.abs(diff)){
                diff = root.val-target;
            }
            if(root.right!=null && root.val<target){
                stack.add(root.right);
            }
            else if(root.left!=null && root.val>target){ 
                stack.add(root.left);
            }
            else if((double)root.val==target){
                return (int)target;
            }
        }
        return (int)(diff+target);
    }
}
```