---
# System prepended metadata

title: 0339. Nested List Weight Sum
tags: [Leetcode, BFS, FaceBook, DFS, Medium]

---

# 0339. Nested List Weight Sum
###### tags: `Leetcode` `FaceBook` `Medium` `DFS` `BFS`
Link: https://leetcode.com/problems/nested-list-weight-sum/
## Code
### DFS
```java=
class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
        return dfs(nestedList, 1);
    }
    public int dfs(List<NestedInteger> nestedList, int depth){
        int ans = 0;
        for(NestedInteger ni:nestedList){
            if(ni.isInteger()){
                ans += depth*ni.getInteger();
            }
            else{
                ans += dfs(ni.getList(), depth+1);
            }
        }
        return ans;
    }
}
```
### BFS 层序遍历
```java=
class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
        Queue<NestedInteger> q = new LinkedList<>();
        q.addAll(nestedList);
        
        int ans = 0;
        int depth = 1;
        while(!q.isEmpty()){
            int size = q.size();
            for(int i = 0;i < size;i++){
                NestedInteger ni = q.poll();
                if(ni.isInteger()){
                    ans += depth*ni.getInteger();
                }
                else{
                    q.addAll(ni.getList());
                }
            }
            depth++;
        }
        return ans;
    }
}
```
## Result
### DFS
Runtime: 0 ms, faster than **100.00%** of Java online submissions for Nested List Weight Sum.
Memory Usage: 36.5 MB, less than **71.23%** of Java online submissions for Nested List Weight Sum.
### BFS
Runtime: 0 ms, faster than **100.00%** of Java online submissions for Nested List Weight Sum.
Memory Usage: 36.5 MB, less than **71.23%** of Java online submissions for Nested List Weight Sum.