0ms Java recursive solution with clear explanation.


  • 0
    S

    Find the closest value is kind of same with Find the Exact Value in a BST.

    public int closestValue(TreeNode root, double target) {
            if (target == root.val) {
                return root.val;
            } else if (target > root.val)  { 
                // if target is larger than root, 
                // the answer can only be 
                // 1. root itself
                // 2. inside the right sub tree
                Integer right = null;
                if (root.right != null) {
                    right = closestValue(root.right,target);
                }
                 return right == null ? root.val : (Math.abs(target - root.val) < Math.abs(target - right) ? root.val : right);
            } else {
                // if target is smaller than root, 
                // the answer can only be 
                // 1. root itself
                // 2. inside the left sub tree.
                Integer left = null;
                if (root.left != null) {
                    left = closestValue(root.left,target);
                }
                 return left == null ? root.val : (Math.abs(target - root.val) < Math.abs(target - left) ? root.val : left);
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.