Nested List Weight Sum


  • 0

    Click here to see the full article post


  • 0
    H

    My non recursive solution:
    public class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
    int ans = 0, depth = 1;
    Queue<List<NestedInteger>> queue = new LinkedList<>();
    queue.offer(nestedList);
    queue.offer(null);
    while(!queue.isEmpty()){
    List<NestedInteger> t = queue.poll();
    if(t == null){
    depth ++;
    if(!queue.isEmpty())
    queue.offer(null);
    continue;
    }
    for(NestedInteger n : t){
    if(n.isInteger()){
    ans = ans + depth * n.getInteger();
    }else{
    queue.offer(n.getList());
    }
    }
    }
    return ans;
    }
    }


  • 0

    The time complexity mentioned here is incorrect. It should be O(N) where N is total number of elements or Integers


Log in to reply
 

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