6ms Java Solution using recursive, how to optimize?


  • 0
    J

    '''
    public int closestValue(TreeNode root, double target) {
    return helper(root, target);
    }

    public int helper(TreeNode n, double target){
        if(n.left==null&&n.right==null) return n.val;
        else if(n.left!=null&&n.right==null){
            if(n.val<target) return n.val;
            else return Math.abs(n.val-target)<Math.abs(helper(n.left,target)-target)?n.val:helper(n.left,target);
        }
       
        else if(n.left==null&&n.right!=null){
            if(n.val>target) return n.val;
            else return Math.abs(n.val-target)<Math.abs(helper(n.right,target)-target)?n.val:helper(n.right,target);
        }
        
        else{
            if(n.val>target)
            return Math.abs(n.val-target)<Math.abs(helper(n.left,target)-target)?n.val:helper(n.left,target);
            if(n.val<target)
            return Math.abs(n.val-target)<Math.abs(helper(n.right,target)-target)?n.val:helper(n.right,target);
            else return n.val;
        }
        
        }

Log in to reply
 

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