10k

270. Closest Binary Search Tree Value

Question

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

Example 1:

img

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

Algorithm

Easy question. Traverse the tree and compare and record the smallest absolute value from the target and the node value.

Code

/**
 * 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 {
    double min = Double.MAX_VALUE;
    int res;
    public int closestValue(TreeNode root, double target) {
        helper(root, target);
        return (int) res;
    }
    
    private void helper(TreeNode root, double target) {
        if (root == null) return;
        helper(root.left, target);
        if (Math.abs(target - root.val) < min) {
            min = Math.abs(target - root.val);
            res = root.val;
        }
        
        helper(root.right, target);
    }
}
Thoughts? Leave a comment