JavaScript - Recursive and Iterative Solution


  • 0
    N

    Recursive:

    var closestValue = function(root, target) {
       var min = root.val;
        
       if(root.val === target) {
           return min;
       }
            
       var search = (target < root.val) ? root.left : root.right;
        
       if(search === null) {
           return min;
       }
        
        var newDiff = closestValue(search, target);
        
       return (Math.abs(min - target) <  Math.abs(newDiff - target)) ? min : newDiff;
    };
    

    Iterative:

    var closestValue = function(root, target) {
        if(root === null) {
           return;
        }
        
        var result = root.val;
        var min = Math.abs(target - root.val);
        
        while(root != null) {
              
            var newMin = Math.abs(target - root.val);
            if(newMin < min) {
               min = newMin;
               result = root.val; 
            }
            
            root = (target <= root.val) ? root.left : root.right;
        }
        
        return result;
    };
    

Log in to reply
 

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