Simple recursive Java AC solution


  • 3
    K
    public int closestValue(TreeNode root, double target) {
        TreeNode parent = root;
        int res=-1;
        if(root.left==null&&root.right==null) return parent.val;
        if(parent.val==target
                    ||(parent.val>target&&parent.left==null)
                    ||(parent.val<target&&parent.right==null)
                    ||(root.left==null&&root.right==null)) return parent.val;
        //search left
        else if(parent.val>target){
            res = closestValue(parent.left,target);
        //search right
        }else{
            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.