O(n) time Java Recursive Solution


  • 0
    public int depthSum(List<NestedInteger> nestedList) {
        return depthSum(nestedList, new Integer[] { 0 }, new Integer[] { 1 });
    }
    
    public int depthSum(List<NestedInteger> nestedList, Integer[] sum, Integer[] depth) {
        for (NestedInteger ni : nestedList) {
            if (ni.isInteger()) {
                sum[0] += depth[0] * ni.getInteger();
            } else {
                depthSum(ni.getList(), sum, new Integer[] { depth[0] + 1 });
            }
        }
        return sum[0];
    }

Log in to reply
 

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