JAVA Solution using Queue


  • 0
    Z

    Inspired by @lop's solution in Nested List Weight Sum, we can solve this problem by Queue as well.

    public class Solution {
        public int depthSumInverse(List<NestedInteger> nestedList) {
            int res = 0;
            ArrayList<Integer> arrayList = new ArrayList<Integer>();
            Queue<NestedInteger> queue = new LinkedList<>(nestedList);
            while(queue.size() > 0){
                int size = queue.size();
                int sum = 0;
                for(int i = 0; i < size; i++){
                    NestedInteger ni = queue.poll();
                    if(ni.isInteger()) sum += ni.getInteger();
                    else queue.addAll(ni.getList());
                }
                arrayList.add(sum);
            }
            
            int level = 1;
            for(int i = arrayList.size() - 1; i >= 0; i--){
                res += arrayList.get(i) * level++;
            }
            return res;
        }
    }
    

Log in to reply
 

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