Short C++ solution

  • 1
    class Solution {
        int depthSum(vector<NestedInteger>& nestedList) {
            return depthSumHelper(nestedList, 1);
        int depthSumHelper(vector<NestedInteger>& nestedList, int depth){
            int ans = 0;
            for(auto nl: nestedList){
                if(nl.isInteger()) ans += depth * nl.getInteger();
                    ans += depthSumHelper(nl.getList(), depth + 1);
            return ans;

  • 0

    There's no need for calling the second function depthSumHelper: you can have an overloading function depthSum with two parameters to represent the second case. Also this other function should be private.

Log in to reply

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