Java Solution: similar to tree level order traversal


  • 35
    L
    public int depthSum(List<NestedInteger> nestedList) {
        if(nestedList == null){
            return 0;
        }
        
        int sum = 0;
        int level = 1;
        
        Queue<NestedInteger> queue = new LinkedList<NestedInteger>(nestedList);
        while(queue.size() > 0){
            int size = queue.size();
            
            for(int i = 0; i < size; i++){
                NestedInteger ni = queue.poll();
                
                if(ni.isInteger()){
                    sum += ni.getInteger() * level;
                }else{
                    queue.addAll(ni.getList());
                }
            }
            
            level++;
        }
        
        return sum;
    }

  • 0
    Y

    awesome solution!


  • 0
    N

    @lop
    what's problem with my version?

    public int depthSum(List<NestedInteger> nestedList) {
        int sum = 0, depth = 1;
        Queue<NestedInteger> queue = new LinkedList<>();
        queue.addAll(nestedList);
        while(!queue.isEmpty())
        {
            for(int i = 0; i < queue.size(); i++)
            {
                NestedInteger n = queue.poll();
                if(n.isInteger())
                    sum += n.getInteger() * depth;
                else
                    queue.addAll(n.getList());
            }
            depth++;
        }
        return sum;
    }

  • 0
    B

    @Nu1L queue size is changing, you need to save the length of next level before the for loop


Log in to reply
 

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