12 lines one pass iterative solution


  • 0
    T

    Use a stack to store list iterator, stack size will be the depth

        public int depthSum(List<NestedInteger> nestedList) {
            Stack<Iterator<NestedInteger>> stack = new Stack<Iterator<NestedInteger>>();
            stack.push(nestedList.iterator());
            int sum = 0;
            while (!stack.isEmpty()) {
                Iterator<NestedInteger> iter = stack.peek();
                if (iter.hasNext()) {
                    NestedInteger ni = iter.next();
                    if (ni.isInteger()) sum += stack.size() * ni.getInteger();
                    else stack.push(ni.getList().iterator());
                } else stack.pop();
            }
            return sum;
        }

Log in to reply
 

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