AC code-Recursion way-with returning Depth

  • 0

    I've saw several discussion code, some of them are brilliant like "add each level integer level times", basically it is the top to bottom solution. My solution is just from bottom to up and return depth each time. All the result add to the num[0], using num[] because it can pass by reference.

    public int depthSumInverse(List<NestedInteger> nestedList) {
       int[] num = new int[1];
       helper(nestedList, num);
       return num[0];
    private int helper(List<NestedInteger> nestedList, int[] num){
        int intSum = 0;
        int depth = 1;
        List<NestedInteger> list = new ArrayList<>();
        for(NestedInteger ni: nestedList){
                intSum += ni.getInteger();
            depth = Math.max(helper(list, num), depth);
        num[0] += intSum*depth;
        return depth + 1;

Log in to reply

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