Java recursive solution


  • 1
    H
    public class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
        return depthSumHelper(nestedList, 1);
    }
    
    public int depthSumHelper(List<NestedInteger> nestedList, int level) {
        int result = 0;
        for(int i = 0; i < nestedList.size(); i++) {
            NestedInteger cur = nestedList.get(i);
            if(cur.isInteger() == true) {
                result += cur.getInteger() * level;
            } else {
                result += depthSumHelper(cur.getList(), level + 1);
            }
        }
        return result;
    }
    

    }


Log in to reply
 

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