By Java Stream/Reduce APIs


  • 0
    X
    public int depthSum(List<NestedInteger> nestedList) {
    	return countDepth(nestedList, 1);
    }
    
    private int countDepth(List<NestedInteger> nestedList, int depth) {
    	BiFunction<Integer, ? super NestedInteger, Integer> accumulator = (sum, e) -> sum
    			+ (e.isInteger() ? e.getInteger() * depth : countDepth(e.getList(), depth + 1));
    	return nestedList.stream().reduce(0, accumulator, (sum1, sum2) -> sum1 + sum2);
    }
    

Log in to reply
 

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