Simple recursive Java AC solution

  • 3
    public int closestValue(TreeNode root, double target) {
        TreeNode parent = root;
        int res=-1;
        if(root.left==null&&root.right==null) return parent.val;
                    ||(root.left==null&&root.right==null)) return parent.val;
        //search left
        else if(parent.val>target){
            res = closestValue(parent.left,target);
        //search right
            res = closestValue(parent.right,target);
        //return the closest value
        return Math.abs(res-target)>Math.abs(target-parent.val)?parent.val:res;

Log in to reply

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