My Java solution using two DFS functions


  • 0
    H
    private int maxDepth;
    
    public int depthSumInverse(List<NestedInteger> nestedList) {
        getDepth(nestedList, 1);
        return helper(nestedList, 1);
    }
    
    private int helper(List<NestedInteger> nestedList, int depth) {
        int sum = 0;
        for (NestedInteger ni: nestedList) {
            if (ni.isInteger())
                sum += ni.getInteger() * (maxDepth - depth + 1);
            else
                sum += helper(ni.getList(), depth + 1);
        }
        return sum;
    }
    
    private void getDepth(List<NestedInteger> nestedList, int depth){
        maxDepth = Math.max(maxDepth, depth);
        for (NestedInteger ni: nestedList) {
            if (!ni.isInteger())
                getDepth(ni.getList(), depth + 1);
        }
    }

  • -2

    failed the test case of [1,[4,[6,[[]] ] ]]


  • 0
    D

    I'm wondering don't you get error in your first line in getDepth() ? you didn't assign any value for maxDepth, and then you call Math.max() on it? correct me if I'm wrong.


  • 0
    H

    In Java, if you don't assign an initial value to an integer global variable, then it will use the default value 0.


  • 0
    D

    oh okay. I didn't know that. Thanks!


Log in to reply
 

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