Java recursion solution.


  • 1

    java recursion.

    public class Solution {
        public int closestValue(TreeNode root, double target) {
            if(root == null) { return target > 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE; }
            if(target < root.val) {
                int l = closestValue(root.left, target);
                return Math.abs(root.val - target) < Math.abs(l - target) ? root.val : l;
            } else {
                int r = closestValue(root.right, target);
                return Math.abs(root.val - target) < Math.abs(r - target) ? root.val : r;
            }
        }
    }
    
    

Log in to reply
 

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