Accepted recursive Javascript solution


  • 0
    R

    Suggestions for improvement welcomed!

    function findBottomLeftValue(root, depth = 0, largest = [ -Infinity, 0 ]) {
        if (!root) {
            return;
        }
    
        findBottomLeftValue(root.left, depth + 1, largest);
    
        if (depth > largest[ 0 ]) {
            largest[ 0 ] = depth;
            largest[ 1 ] = root.val;
        }
    
        findBottomLeftValue(root.right, depth + 1, largest);
    
        return largest[ 1 ];
    }
    
    
    

  • 0
    J

    I think this solution makes sense but storing the values in arrays is not very intuitive. I've amended this slightly to make things more readable. Other than that good work.

    var findBottomLeftValue = function(root, depth = 0, valueObj = {depth: -Infinity, val: 0}) {
        if (!root) {
            return;
        }
        
        findBottomLeftValue(root.left, depth + 1, valueObj)
    
        if (depth > valueObj.depth) {
            valueObj.depth = depth;
            valueObj.val = root.val
        }
        
        findBottomLeftValue(root.right, depth + 1, valueObj) 
    
        return valueObj.val;   
    };

Log in to reply
 

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