Easy and clean recursive solution, beats 100 % JavaScript Solutions


  • 0
    K

    The idea is to increment the depth of the nestedList at each iteration and assign the depth to its next nestedList if there exists.

    var depthSum = function(nestedList) {
    	var sum = 0;
    	if(nestedList.depth) nestedList.depth += 1;
    	else nestedList.depth = 1;
    	for(var i = 0; i < nestedList.length; i++){
    		var integerNested = nestedList[i];
    		if(integerNested.isInteger()){
    			sum += nestedList.depth * integerNested.getInteger();
    		}
    		else{
    			var list = integerNested.getList();
    			list.depth = nestedList.depth;
    			sum += depthSum(list);
    		}
    	}
    	
    	return sum;
        
    };
    

Log in to reply
 

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